Home > Back-end >  Is there a specific order in which objects are merged in js?
Is there a specific order in which objects are merged in js?

Time:10-27

So I was watching a course and stumbled on a method called Object.assign() which merges two objects together. But since objects are orderless, I was wondering in which order the properties of the objects would be merged. Kudos to any good answers.

CodePudding user response:

Later sources will overwrite objects from left to right, from MDN Object.assign:

Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.

For example, the id property in the target object will be overwritten here, so the final id will be as the second (source) object.

const result = Object.assign({ id: 1, foo: 'bar' }, { id: 2 });
console.log(result)
    
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

The spec is your friend. It tells us that Object.assign takes each of the source objects in turn from left to right, enumerates the enumerable [[OwnPropertyKeys]] of those objects, and shallow copies the value associated with each property key onto the target object.

Object properties are enumerated in the following order:

  1. Nonnegative integer-style properties in ascending order
  2. All other string properties in creation order
  3. Symbol properties in creation order

However, it is good practice to normally treat object properties as unordered and, if you need an ordered hash-table-kind-of-thing, use a Map.

For most uses of Object.assign, "put the most important source object on the right-hand side" does what you need to do.

const result = Object.assign(target, source, moreImportantSource, mostImportantSource)

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Try It

    const target = { a: 1, b: 2 };
    const source = { b: 4, c: 5 };
    
    const returnedTarget = Object.assign(target, source);
    
    console.log(target);
    // expected output: Object { a: 1, b: 4, c: 5 }
    
    console.log(returnedTarget === target);
    // expected output: true
  • Related