Boky
Boky

Reputation: 12084

Update some object properties

I have something like this :

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

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

How can I update test with test1? Thus, what I want to get is :

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

Upvotes: 1

Views: 62

Answers (2)

alexhoma
alexhoma

Reputation: 362

You can do this:

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

Actually, you don't need to put the object as an array. Like this:

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

This way, you don't need to call it like this: test[0].name --> just do test.name

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386868

You could use Object.assign for it.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

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);

Upvotes: 5

Related Questions