Javascript 2个对象数组,从一个对象数组中获取一个值,并将其分配给另一个对象数组

时间:2019-02-10 15:40:49

标签: javascript arrays reactjs javascript-objects react-select

所以我有2个对象数组,我想从一个对象中获取名称值,并将其分配给label和value。这就是我在做什么。

let newAreas = [{ label: '', value: '' }];
let areas = [{name: 'Haram', condition: true, counter: 5}, {name: 'Nasr City', condition: false, counter: 3}, {name: 'Faisl', condition: true, counter: 7}];  

我想获取每个名称并将其分配给标签和值,所以现在循环

areas.map(area => {
      newAreas.map(val => {
        val.label = area.name;
        val.value = area.name;
  });
});

    console.log(newAreas);

但这只会让我获得最后的价值我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

您只想使用一次map,然后检索返回的值:

const areas = [
  {name: 'Haram', condition: true, counter: 5}, 
  {name: 'Nasr City', condition: false, counter: 3}, 
  {name: 'Faisl', condition: true, counter: 7}
];

const newAreas = areas.map(({name}) => ({label: name, value: name}));

console.log(newAreas);

这利用了object destructuring