Sum json object with pure js

Asked

Viewed 232 times

1

I have the following object

json1:{A:1, B:2}
json2:{A:4, C:3} 

How do I make the json1 receive the data from json2, replacing if he finds an equal key and moving if he doesn’t find it, more or less so than the json1 would have resulted:

json1:{A:4, B:2, C:3}

2 answers

3


If you want to replace all values of json2 in json1 then you just need to go through your keys with Object.keys and apply the value to each key. This way the ones that exist will be replaced and the ones that are not added

Example:

let obj1 = {A:1, B:2};
let obj2 = {A:4, C:3};

for (let chave of Object.keys(obj2)){
  obj1[chave] = obj2[chave];
}

console.log(obj1);

2

You can also use Object.assign to "merge" two objects, for example:

let obj1 = {A:1, B:2};
let obj2 = {A:4, C:3};

obj1 = Object.assign(obj1, obj2)

console.log(obj1);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.