Combine Two Objects in Javascript

To combine two objects in javascript, we can use the code section given below

const posts = { ‘2018-05-11’: { posts: 2 }, ‘2018-05-12’: { posts: 5 }};
const notes = { ‘2018-05-11’: { notes: 1 }, ‘2018-05-12’: { notes: 3 }};

function objCombine(obj, variable) {
for (let key of Object.keys(obj)) {
if (!variable[key]) variable[key] = {};

for (let innerKey of Object.keys(obj[key]))
  variable[key][innerKey] = obj[key][innerKey];

}
}

let combined = {};
objCombine(posts, combined);
objCombine(notes, combined);
console.log(combined)

Leave a comment

Your email address will not be published. Required fields are marked *