How to dynamically merge two JavaScript object properties

Asked 2 years ago, Updated 2 years ago, 115 views

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

I'd like to dynamically merge the two object properties as in the example above. I don't know what to do. Please tell me the simplest way.

javascript merge

2022-09-22 22:05

1 Answers

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } If you do this simply, obj1 has the property of obj2. If you don't want obj1 to be modified

function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

You can do it this way.


2022-09-22 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.