我正在尝试向对象添加属性,但是仅附加了最后一个

时间:2019-11-18 19:45:50

标签: javascript

我想用来自其他对象的值创建该对象

let arr = [
  { name: "Ashley", n: 241 },
  { name: "Deborah", n: 347 },
  { name: "Jessica", n: 307 }
];

let arr = [];
graphData.forEach(e => {
  arr.push(e);
  if(arr.length === 7){
    let o = {};
    arr.forEach(a => {
      let name = e.name;
      o[name] = +a.n
    });
    o["chartDate"] = new Date(e.chartDate);
    this.data.push(o);
    arr = [];
  }
});

而不是

{ 
   Ashley: 241,
   Deborah: 347,
   Jessica: 307 
}

我只得到最后一个财产

{ 
   Jessica: 307 
}

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

在这种情况下我总是使用reduce

let arr = [
  { name: "Ashley", n: 241 },
  { name: "Deborah", n: 347 },
  { name: "Jessica", n: 307 }
];

const obj =  arr.reduce((prev, curr) => {
  prev[curr.name] = curr.n;
  return prev;
}, {});

console.log(obj);

答案 1 :(得分:1)

尝试修复您的代码:

let arr = [
  { name: "Ashley", n: 241 },
  { name: "Deborah", n: 347 },
  { name: "Jessica", n: 307 }
];

let o = {};
arr.forEach(a => {
  let name = a.name;
  o[name] = a.n
});
console.log(o);