将一个键的值和值添加到数组中的另一个属性

时间:2018-08-21 06:59:14

标签: javascript ecmascript-6

const array = [{
    id: 1,
    name: 'Bob',
    education: [{
      degree: 'bachelors',
      Major: 'computers'
    }, {
      degree: 'masters',
      Major: 'computers'
    }]
  },
  {
    id: 2,
    name: 'Alice',
    education: [{
      degree: 'bachelors',
      Major: 'electronics'
    }, {
      degree: 'masters',
      Major: 'electronics'
    }]
  }
];


const resultArray = [{
    id: 1,
    name: 'Bob',
    education: [{
      degree: 'bachelors',
      Major: 'computers',
      id: 1
    }, {
      degree: 'masters',
      Major: 'computers',
      id: 1
    }]
  },
  {
    id: 2,
    name: 'Alice',
    education: [{
      degree: 'bachelors',
      Major: 'electronics',
      id: 2
    }, {
      degree: 'masters',
      Major: 'electronics',
      id: 2
    }]
  }
];

我希望将id及其数组的值添加到education数组对象中。你能建议我怎么做吗?

谢谢

3 个答案:

答案 0 :(得分:1)

您只需要循环到array即可将每个对象放入array中,然后通过循环{{1}将id值添加到education数组中}}数组。您可以使用简单的education循环或for,因为更改对象中的任何对象属性都会反映原始对象。

使用Array.forEach()

forEach()

使用const array = [{ id: 1, name: 'Bob', education: [{ degree: 'bachelors', Major: 'computers' }, { degree: 'masters', Major: 'computers' }] }, { id: 2, name: 'Alice', education: [{ degree: 'bachelors', Major: 'electronics' }, { degree: 'masters', Major: 'electronics' }] }]; array.forEach((item) => { item.education.forEach((educationObj) => { educationObj['id'] = item.id; }); }); console.log(array);

for

答案 1 :(得分:0)

好吧,您只需要嵌套的 .map() method 调用即可执行此操作:

const resultArray = array.map(x => {
  x.education = x.education.map(e => {
    e.id = x.id;
    return e;
  });
  return x
});

第一个.map()调用是循环和转换原始array 第二个内部.map()用于更新和转换内部education数组。

演示:

const array = 
      [{ id: 1, name: 'Bob', education: [{degree: 'bachelors', Major: 'computers'}, {degree: 'masters', Major: 'computers'}] },
       { id: 2, name: 'Alice', education: [{degree: 'bachelors', Major: 'electronics'}, {degree: 'masters', Major: 'electronics'}] }];

const resultArray = array.map(x => {
  x.education = x.education.map(e => {
    e.id = x.id;
    return e;
  });
  return x
});

console.log(resultArray);

答案 2 :(得分:-2)

您可以使用嵌套地图来解决它。

const resultArray = array.map((arr) => {
  array.education = arr.education.map((e) => {
   e.id = arr.id;
   return e;
 });
 return arr;
});