es6 merge objects code example

Example 1: 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 2: 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 3: merge objects javascript es6

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well

console.log(newItem );

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" }

Example 5: react merge two objects

const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}

const object3 = {...object1, ...object2 }