javascript mapp code example

Example 1: javascript map function

const posts = [
  { id: 1, title: "Sample Title 1", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
  { id: 2, title: "Sample Title 2", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
  { id: 3, title: "Sample Title 3", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
];
// ES2016+
// Create new array of post IDs. I.e. [1,2,3]
const postIds = posts.map((post) => post.id);
// Create new array of post objects. I.e. [{ id: 1, title: "Sample Title 1" }]
const postSummaries = posts.map((post) => ({ id: post.id, title: post.title }));

// ES2015
// Create new array of post IDs. I.e. [1,2,3]
var postIds = posts.map(function (post) { return post.id; });
// Create new array of post objects. I.e. [{ id: 1, title: "Sample Title 1" }]
var postSummaries = posts.map(function (post) { return { id: post.id, title: post.title }; });

Example 2: array mdn map

let new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])

Example 3: map javascript

var kvArray = [["clave1", "valor1"], ["clave2", "valor2"]];

// El constructor por defecto de Map para transforar un Array 2D (clave-valor) en un mapa
var miMapa = new Map(kvArray);

miMapa.get("clave1"); // devuelve "valor1"

// Usando la función Array.from para transformar el mapa a un Array 2D clave-valor.
console.log(Array.from(miMapa)); // Muestra exactamente el mismo Array que kvArray

// O usando los iteradores de claves o valores y convirtiendo a array.
console.log(Array.from(miMapa.keys())); // Muestra ["clave1", "clave2"]