Aria
Aria

Reputation: 55

From an array of objects, extract value of two properties into an array

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

Upvotes: 1

Views: 5238

Answers (2)

Peter Hull
Peter Hull

Reputation: 7077

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

Upvotes: 2

guijob
guijob

Reputation: 4488

arr.map(({foo, anotherfoo}) => ({foo, anotherfoo}))

Upvotes: 3

Related Questions