Skip to content
Fix Code Error

How can I merge properties of two JavaScript objects dynamically?

March 13, 2021 by Code Error
Posted By: JC Grubbs

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.

Solution

ECMAScript 2018 Standard Method

You would use object spread:

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

merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1.

/** There's no limit to the number of objects you can merge.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

Here is also the MDN documentation for this syntax. If you’re using babel you’ll need the babel-plugin-transform-object-rest-spread plugin for it to work.

ECMAScript 2015 (ES6) Standard Method

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(see MDN JavaScript Reference)


Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

If you’re using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

Example function:

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
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;
}
Answered By: John Millikin

Related Articles

  • How to avoid exhaustive matching and directly return…
  • Group array of objects by multiple keys using d3.groups
  • What is the difference between up-casting and…
  • I want to solve the javascript OOP problems, but my…
  • How do I include certain conditions in SQL Count
  • C# Only allow one class to call a different class's…
  • Merge object with Vuejs and Axios
  • Java method: Finding object in array list given a…
  • C++ cast to derived class
  • Create new dataframe column with numbered time windows
  • Vue - Deep watch change of array of objects, either…
  • [Vue warn]: Error in render: "TypeError: Converting…
  • TypeError for every array of objects after index 0
  • Type Checking: typeof, GetType, or is?
  • getting unique value from object using Javascript
  • react-table has a issue with rendering in next.js
  • Confused about the Visitor Design Pattern
  • How to prevent scrolling the whole page?
  • Getting infinite loop after entering 2 objects to…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • backbone.js models pointing to same instance of nested model
  • Convert Daily Data into Weekly Data and summarize…
  • Generic deep diff between two objects
  • run function with uniquie value using javascript / node js
  • Why do we need virtual functions in C++?
  • SQL query return data from multiple tables
  • R: How can I create rows based on the values of other rows?
  • What is the 'new' keyword in JavaScript?
  • (Java) Static member accessed via instance reference…
  • How to disable/enable select field using jQuery?
  • R- Calculate rolling mean from values match a column…
  • Setting up and using Meld as your git difftool and mergetool
  • Aurelia UX showcase app fails to load
  • Does moment.js allow me to derive a timezone…
  • Backbone.js Uncaught TypeError this.model.each is…
  • how create a simple object animation in processing
  • Dodged bar plot in R based on to columns with count…
  • Javascript behaviour while using parameter of method…
  • @DataProvider with return type as Iterator
  • Room @Relation with two foreign keys
  • C# Randomize inherited class without hardcoding
  • Why do we use __init__ in Python classes?
  • Ember computed property doesn't update when…
  • sorting an array by using pointer arithmetic
  • How to get a value inside an ArrayList java
  • How to use setOnAction with checkBox?
  • Marionette-Backbone how do I make a grid table with…
  • Casting errors which occur in my JAVA code
  • PUT and POST getting 405 Method Not Allowed Error…
  • Updating an object with setState in React
  • calling an abstract method in a concrete method…
  • Three.js: Cannot display mesh created with texture array
  • Counter of instances for a Class Tree
  • Working with 'single file' Vue.js components in…
  • Using templates as select option name in Aurelia
  • Is recursion ever faster than looping?
  • How can I represent an 'Enum' in Python?
  • For-each over an array in JavaScript
  • Uncaught TypeError: c.querySelectorAll is not a function
  • Cloning an Object in Node.js
  • Static Vs. Dynamic Binding in Java
  • convert a html table with select to Json
  • Computed values in a object | Svelte
  • Merge (Concat) Multiple JSONObjects in Java
  • Vue.js - emit to update array not working
  • Java create new instance of class based on another class
  • Dependent/Cascading Dropdowns in Aurelia
  • How to get nested JSON data in vue.js
  • Failed to configure a DataSource: 'url' attribute is…
  • How do I make the method return type generic?
  • Polymer static variable listener?
  • Vuetify grid system row management
  • Polymer: Vers simple data binding doesn't work in…
  • How to Deserialize XML document
  • Best way to update an element in a generic List
  • Aurelia CLI, babel runtime and async transforms
  • Expecting ConcurrentModificationException but…
  • Vuetify grid column wrap fill full height
  • Polymer 1.0+ notify true not working
  • What does this symbol mean in JavaScript?
  • Peak signal detection in realtime timeseries data
  • Vue.js inline template not displaying data
  • Difference between "this" and"super" keywords in Java
  • Print all properties of a Python Class
  • Table fixed header and scrollable body
  • Replace every other instance of a string
  • How to create a box plot for a grouped data
  • Node.js ES6 classes with require
  • JavaScript hashmap equivalent
  • How to group data from attributes using for loops in VueJS
  • How do I display a single oject from an array in VueJs?
  • Backbone.js get and set nested object attribute
  • Replace multiple strings with multiple other strings
  • Recommended way to insert elements into map
  • How do I get my react app to display object…
  • IEnumerable vs List - What to Use? How do they work?
  • What are forward declarations in C++?
  • Possible to use a let within an if/cond?
  • print arraylist element?
  • Problem with acces to function with react javascript…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Trigger a button click with JavaScript on the Enter key in a text box

Next Post:

Altering a column: null to not null

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error