how to map more than one property from array of object in javascript

user144271 picture user144271 · Dec 11, 2018 · Viewed 15.9k times · Source

I have an array of Object as follows:

var obj = [
  {a: 1, b: 5, c: 9},
  {a: 2, b: 6, c: 10},
  {a: 3, b: 7, c: 11},
  {a: 4, b: 8, c: 12}
];

I know about how to get single object using Array.map() like this.

var result = obj.map(x=>x.a)

This will give me following result

[1, 2, 3, 4]

But I want result like follows:

[
  {a: 1, b: 5},
  {a: 2, b: 6},
  {a: 3, b: 7},
  {a: 4, b: 8}
]

inshort from array of object i want to select only few fields(more than one)

how to do that ?

Answer

Mohammad Usman picture Mohammad Usman · Dec 11, 2018

You can use .map() with Object Destructuring:

let data = [
    {a:1,b:5,c:9}, {a:2,b:6,c:10},
    {a:3,b:7,c:11}, {a:4,b:8,c:12}
];
          
let result = data.map(({ a, b }) => ({a, b}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }