Add json object with pure js

1

I have the following object

json1:{A:1, B:2}
json2:{A:4, C:3} 
How do I get json1 to get data from json2 , overriding if it finds an equal key and moving if it does not find, more or less what json1 would result in:

json1:{A:4, B:2, C:3}
    
asked by anonymous 14.03.2018 / 13:44

2 answers

3

If you want to replace all values from json2 to json1 then you just need to move your keys with Object.keys and apply the value to each key. In this way those that exist will be replaced and those 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);
    
14.03.2018 / 13:50
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);
    
14.03.2018 / 19:50