如何从具有多个数组的大对象中获取特定的键值

时间:2018-12-05 06:57:49

标签: javascript arrays node.js sails.js

我正在使用sailjs 1.0并从api接收对象,如下所示。.但是我只需要该对象的特定数据。

var constructicons = [
  {
    name: 'Scrapper',
    form: 'Freightliner Truck',
    team: 'Decepticon',
    bodyPart: 'rightLeg'
  },
  {
    name: 'Hook',
    form: 'Mobile Crane',
    team: 'Decepticon',
    bodyPart: 'upperTorso'
  },
  {
    name: 'Bonecrusher',
    form: 'Bulldozer',
    team: 'Decepticon',
    bodyPart: 'leftArm'
  },
  {
    name: 'Scavenger',
    form: 'Excavator',
    team: 'Decepticon',
    bodyPart: 'rightArm'
  },
  {
    name: 'Mixmaster',
    form: 'Concrete Mixer',
    team: 'Decepticon',
    bodyPart: 'leftLeg'
  },
  {
    name: 'Long Haul',
    form: 'Dump Truck',
    team: 'Decepticon',
    bodyPart: 'lowerTorso'
  }
];

现在我只需要所有数组的namebodyPart键值吗?我该如何实现?

1 个答案:

答案 0 :(得分:1)

您可以简单地使用Array.map()

let constructicons = [ { name: 'Scrapper', form: 'Freightliner Truck', team: 'Decepticon', bodyPart: 'rightLeg' }, { name: 'Hook', form: 'Mobile Crane', team: 'Decepticon', bodyPart: 'upperTorso' }, { name: 'Bonecrusher', form: 'Bulldozer', team: 'Decepticon', bodyPart: 'leftArm' }, { name: 'Scavenger', form: 'Excavator', team: 'Decepticon', bodyPart: 'rightArm' }, { name: 'Mixmaster', form: 'Concrete Mixer', team: 'Decepticon', bodyPart: 'leftLeg' }, { name: 'Long Haul', form: 'Dump Truck', team: 'Decepticon', bodyPart: 'lowerTorso' } ];

let result = constructicons.map(({name,bodyPart})=>({name,bodyPart}));
console.log(result);