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

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 ?


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; }

If, as in your example, you want to exclude a particular property or few, you can use destructuring and use rest properties to create an object with only the properties you want:

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}
];
const mapped = obj.map(({ c, ...rest }) => rest);
console.log(mapped);

If you want to include properties, simply extract them from the .map callback:

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}
];
const mapped = obj.map(({ a, b }) => ({ a, b }));
console.log(mapped);

Use map():

var 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 modified = data.map(obj => ({a: obj.a, b: obj.b}))

console.log(modified);

Or if you prefer destructuring:

var 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 modified = data.map(({ a, b }) => ({a, b}));

console.log(modified);

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}
];

var result = obj.map(e => ({a:e.a , b:e.b}));
console.log(result)

You can return a custom object with required properties using map()

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}
          ];
          
          
let op = obj.map(e => {
   return { a:e.a, b: e.b };
})        

console.log(op);