javascript combine two objects 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: merge objects javascript

const a = { b: 1, c: 2 };
const d = { e: 1, f: 2 };

const ad = { ...a, ...d }; // { b: 1, c: 2, e: 1, f: 2 }

Example 3: 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 4: how to merge two objects into one in javascript

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

let mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

Example 5: javascript combine objects

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

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

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