1

Consider a JavaScript object array with the following structure: objArray = [ { foo: 1, bar: 2, anotherfoo:5}, { foo: 3, bar: 4, anotherfoo: 8}];

How can I use map to extract foo and anotherfoo into a new array. Possible duplicate of

Peter Hull
  • 6,683
  • 4
  • 39
  • 48
Aria
  • 55
  • 1
  • 10

2 Answers2

3
arr.map(({foo, anotherfoo}) => ({foo, anotherfoo}))
guijob
  • 4,413
  • 3
  • 20
  • 39
2

This should work - if your elements don't have a foo or anotherfoo they'll come out as undefined

objArray = [{
  foo: 1,
  bar: 2,
  anotherfoo: 5
}, {
  foo: 3,
  bar: 4,
  anotherfoo: 8
}];

function myfunction(arr) {
  return arr.map(function(e) {
    return {
      foo: e.foo,
      anotherfoo: e.anotherfoo
    };
  });
}

newArray = myfunction(objArray);
console.log(newArray);

// newArray is [{foo:1, anotherfoo:5},{foo:3, anotherfoo:8}]

If you're using modern JS (ES6 I think) you can use 'object destructuring'

function myfunction2(arr) {
  return arr.map(({foo, anotherfoo}) => 
                 ({foo, anotherfoo}));
}

to be honest I think the old way is clearer in intent.

To address your comment - if you want to do some further processing - it's easy if you just need one element at a time. That's what Array.map does, it breaks the array into its elements, runs a function on each one, and re-assembles the return values into another array of the same size.

function myfunction(arr) {
  return arr.map(function(e) {
    var newfoo;
    if(e.foo==="something") {newfoo = anotherfoo+1;} else{newfoo = anotherfoo-1;}
    return {
      foo: e.foo,
      anotherfoo: newfoo
    };
  });
}

and with destructuring

function myfunction2(arr) {
  return arr.map(({foo, anotherfoo}) => {
                   if(foo==="something") {anotherfoo+=1} else{anotherfoo -=1};
                   return {foo, anotherfoo}});
}

Obviously if your processing function gets too big you can break it out into another standalone function instead of giving an anonymous function to map

Peter Hull
  • 6,683
  • 4
  • 39
  • 48
  • Great answer. If I want to do some calculation on the properties of the object array how to do it. Something like if(foo==="something") {anotherfoo+=1} else{anotherfoo -=1}. and then return with the same structure as before. – Aria Jan 17 '19 at 16:46