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

2
  • From your example, what would you want the output to be? myfunction(objArray) == what? Commented Jan 16, 2019 at 22:24
  • I need another array to have this output: newArray=[{foo:1, anotherfoo:5},{foo:3, anotherfoo:8}] Commented Jan 17, 2019 at 14:26

2 Answers 2

3
arr.map(({foo, anotherfoo}) => ({foo, anotherfoo}))
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.