How to map a JavaScript object?

In this post we are gonna look in to ways to map an object in JavaScript.

The object type represents one of the JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the object() constructor or the object initializer/ literal syntax.

If you wanna know more about what JavaScript object is. Visit here

let obj = {
  1: "apple",
  2: "banana",
  3: "chocolate",
};
 let x = Object.keys(obj).map((item) => {
  return obj[item];
});
console.log(x);
//[ 'apple', 'banana', 'chocolate' ]


if you want to get a two dimensional array with key value pairs. you can use the following method.


let obj = {
  1: "apple",
  2: "banana",
  3: "chocolate",
};
 let x  = { a: 1, b: 2, c: 3 };
 const mapped = Object.entries(obj).map(([key, value]) => [key, value]);
 //[ [ '1', 'apple' ], [ '2', 'banana' ], [ '3', 'chocolate' ] ]




Comments