解构对象数组

时间:2019-01-11 17:02:46

标签: javascript

我想根据某些键/值对过滤现有的对象数组。在下面的示例中,我希望结果是一个只有id和def字段的对象的新数组(假定对象中可以有n个字段,因此我不想显式删除abc)。但是,如果我像下面这样编码,则看起来必须手动逐行手动构建新数组。有没有一种简单的班轮?

  const someArray = [
   {id: 1, abc: 2, def: 3},
   {id:4, abc: 6, def: 8},
   {id: 5, abc: 7, def: 9},
  ];
  const [array0, array1, array2] = someArray;
  const onlyOneRow = (({ id, def }) => ({ id, def }))(array0);

2 个答案:

答案 0 :(得分:1)

这可以通过map()方法轻松生成:

const someArray = [
    {id: 1, abc: 2, def: 3},
    {id:4, abc: 6, def: 8},
    {id: 5, abc: 7, def: 9},
];

let res = someArray.map(x => {return {id: x.id, def: x.def}});

console.log(res);

答案 1 :(得分:-1)

您可以使用filter来构建满足您需要的新数组。考虑以下示例:

var array1 = [
  {id: 1, abc: 2, def: 3},
  {id:4, abc: 6, def: 8},
  {id: 5, abc: 7, def: 9},
];

// pass a function to filter
const filteredArray = array1.filter(({id,def}) => x.id == 4);

console.log(filteredArray);
// expected output: Array [{id:4, abc: 6, def: 8}]

,如果您需要在此过滤后的数组中更改值,则可以使用map:

const mappedArray = output.map(x => {id: x.id, def: x.def});

console.log(mappedArray);
// expected output: Array [{id:4, def: 8}]