merge object values javascript code example

Example 1: javascript merge objects

var person={"name":"Billy","age":34};
var clothing={"shoes":"nike","shirt":"long sleeve"};

var personWithClothes= Object.assign(person, clothing);//merge the two object

Example 2: merge objects js

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

Example 3: javascript combine objects

const obj1 = {'a': 1, 'b': 2};
const obj2 = {'c': 3};
const obj3 = {'d': 4};

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

Example 4: javascript merge objects

// reusable function to merge two or more objects
function mergeObj(...arr){
  return arr.reduce((acc, val) => {    
    return { ...acc, ...val  };
  }, {});
}

// test below

const human = { name: "John", age: 37 };

const traits = { age: 29, hobby: "Programming computers" };

const attribute = { age: 40, nationality: "Belgian" };

const person = mergeObj(human, traits, attribute);
console.log(person);
// { name: "John", age: 40, hobby: "Programming computers", nationality: "Belgian" }