Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Web Technology by (47.6k points)

I need to be able to merge two (very simple) JavaScript objects at runtime. For example, I'd like to:

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

var obj2 = { animal: 'dog' } 

obj1.merge(obj2); 

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

Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

1 Answer

0 votes
by (106k points)
edited by

If you want to merge properties of two JavaScript objects dynamically you would use object spread:

let merged = {...obj1, ...obj2};

OR

const allRules = {...obj1, ...obj2, ...obj3};

Want to become a Web Developer, here are Web Development Courses for you! 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 18, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 12, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...