如何添加元素键&对象的价值?

时间:2018-05-08 02:45:59

标签: javascript arrays algorithm

我正在尝试将键值从数组添加到person对象,我在代码下面模拟了类似的方法,当我们将键/值对分配给对象时它将来到未定义的对象。什么是正确的方法来实现这一任务?

main.js

const person = {
    Name: "John klmeni"
    age: 29 
} 

const address = [{address: '111 main st"}] 
for (let obj in person) {
    address.forEach(element ,==> {
        obj[key] = element.key
    }
}

1 个答案:

答案 0 :(得分:2)

我想你想做以下事情?



const person = {
  Name: "John klmeni",
  age: 29 
} 

const address = [{address: '111 main st'}];
const newPerson = address.reduce(
  (result,item)=>
    Object.assign({},result,item),
  person
);
console.log(newPerson);