从对象数组中,将两个属性的值提取到数组中

时间:2019-01-16 22:16:14

标签: javascript arrays

考虑具有以下结构的JavaScript对象数组: objArray = [ { foo: 1, bar: 2, anotherfoo:5}, { foo: 3, bar: 4, anotherfoo: 8}];

如何使用map将foo和anotherfoo提取到新数组中。  Possible duplicate of

2 个答案:

答案 0 :(得分:1)

这应该有效-如果您的元素没有Comparablefoo,它们将以anotherfoo出现

undefined

如果您使用的是现代JS(我认为是ES6),则可以使用“对象解构”

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

说实话,我认为旧方法意图更清晰。

要发表您的评论-如果您想做进一步处理-如果一次只需要一个元素,这很容易。这就是function myfunction2(arr) { return arr.map(({foo, anotherfoo}) => ({foo, anotherfoo})); } 的工作,它将数组分解为元素,在每个元素上运行一个函数,然后将返回值重新组合为另一个相同大小的数组。

Array.map

并具有破坏性

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

很明显,如果您的处理函数太大,则可以将其分解为另一个独立函数,而不是将匿名函数提供给function myfunction2(arr) { return arr.map(({foo, anotherfoo}) => { if(foo==="something") {anotherfoo+=1} else{anotherfoo -=1}; return {foo, anotherfoo}}); }

答案 1 :(得分:1)

arr.map(({foo, anotherfoo}) => ({foo, anotherfoo}))
相关问题