乐闻世界logo
搜索文章和话题

How can i merge properties of two javascript objects dynamically

4个答案

1
2
3
4

In JavaScript, we can dynamically merge properties of two objects using multiple approaches. The most common methods involve the spread operator (...) and the Object.assign method. Below are examples illustrating both techniques:

Using the Spread Operator (...)

The spread operator enables us to concisely copy all enumerable properties from one object into a new object. Here is an example:

javascript
const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = { ...object1, ...object2 }; console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }

In this example, object1 and object2 are merged into mergedObject. Since both objects contain the property b, the value from object2 overrides the value from object1 because it is specified later in the spread operation.

Using the Object.assign Method

The Object.assign method copies all enumerable own properties from one or more source objects to a target object and returns the modified target object. Here is an example:

javascript
const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = Object.assign({}, object1, object2); console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }

In the above example, we first create an empty object {} as the target, then copy properties from object1 and object2 into it. Similar to the spread operator, if duplicate properties exist, the later source objects override the earlier source objects' properties.

Key Considerations

When dynamically merging objects, note the following:

  1. Both the spread operator and Object.assign perform a shallow copy. This means that if an object property is a complex type (e.g., an array or another object), the merged object shares the reference to this property with the source objects.
  2. For deep copy merges, consider using a recursive strategy or a library like lodash's _.merge function to ensure nested objects are also merged.
  3. If merged objects contain duplicate properties, the values from later objects override those from earlier objects.

Selecting the appropriate merge strategy based on your application context is essential, and when handling large or complex objects, also evaluate performance and memory implications.

2024年6月29日 12:07 回复

Note that the extend method from underscore.js performs this operation in a single line:

shell
_.extend({name : 'moe'}, {age : 50}); => {name : 'moe', age : 50}
2024年6月29日 12:07 回复

jQuery also provides a utility: http://api.jquery.com/jQuery.extend/.

From the jQuery documentation:

javascript
// Merge the options object into the settings object var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options); // The content of the settings object is now: // { validate: true, limit: 5, name: "bar" }

The above code modifies the existing object named settings.


If you want to create a new object without modifying any of the original objects, use the following command:

javascript
var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; /* Merge defaults and options without modifying defaults */ var settings = $.extend({}, defaults, options); // The content of the settings variable is now: // {validate: true, limit: 5, name: "bar"} // The 'defaults' and 'options' variables remained the same.
2024年6月29日 12:07 回复

ECMAScript 2018 Standard Approach

You will use object spread:

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

merged is the union of obj1 and obj2, with properties from obj2 overriding those from obj1.

shell
/** 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 the MDN documentation for this syntax. If you use Babel, you need the @babel/plugin-proposal-object-rest-spread plugin to work properly (this plugin is included in @babel/preset-env for ES2018).

ECMAScript 2015 (ES6) Standard Approach

shell
/* 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)


ES5 and Earlier Versions Approach

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

Note that if you still want to use the unmodified obj1, you should be cautious.

If the framework you're using messes up your prototypes extensively, you must use checks like hasOwnProperty, but this code works for 99% of cases.

Example function:

shell
/** * 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; }

Also: Check this program to see the differences between Object.assign and spread syntax object literals.

2024年6月29日 12:07 回复

你的答案