最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - From an array of objects, extract value of two properties into an array - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Jan 17, 2019 at 16:29 Peter Hull 7,0975 gold badges43 silver badges52 bronze badges asked Jan 16, 2019 at 22:16 AriaAria 551 silver badge10 bronze badges 2
  • From your example, what would you want the output to be? myfunction(objArray) == what? – Peter Hull Commented Jan 16, 2019 at 22:24
  • I need another array to have this output: newArray=[{foo:1, anotherfoo:5},{foo:3, anotherfoo:8}] – Aria Commented Jan 17, 2019 at 14:26
Add a ment  | 

2 Answers 2

Reset to default 3
arr.map(({foo, anotherfoo}) => ({foo, anotherfoo}))

This should work - if your elements don't have a foo or anotherfoo they'll e 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 ment - 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

发布评论

评论列表(0)

  1. 暂无评论