更新一些对象属性

时间:2016-10-02 15:38:23

标签: javascript

我有这样的事情:

let test = [
             {
              name: "Mark",
              address: "Some adress",
              company: "company name",
              age: 21
             }
]

let test1 = [
             {
              name: "Steve",
              age: 27
             }
    ]

如何使用test1更新测试?因此,我想得到的是:

let test2 = [
             {
              name: "Steve",
              address: "Some adress",
              company: "company name",
              age: 27
             }
]

2 个答案:

答案 0 :(得分:5)

您可以使用Object.assign

  

Object.assign() 方法用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。



let test = [{ name: "Mark", address: "Some adress", company: "company name", age: 21 }],
    test1 = [{ name: "Steve", age: 27 }];

Object.assign(test[0], test1[0]);

console.log(test);




答案 1 :(得分:0)

你可以这样做:

test[0].name = test1[0].name;
test[0].age = test1[0].age;

实际上,您不需要将对象作为数组。像这样:

let test = {
      name: "Mark",
      address: "Some adress",
      company: "company name",
      age: 21
}

这样,您无需像这样调用它:test[0].name - >只需test.name