how to merge 2 objects in javascript code example

Example 1: merge two objects javascript

const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}
const object3 = {...object1, ...object2 } //{name: "Flavio", age: 35}

Example 2: 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" }