Merging two javascript objects into one? [duplicate]
var x = {posts: 2};var y = {notes: 1};var z = Object.assign( {}, x, y );console.log(z);
Use Object.assign()
and assign object properties to empty object.
You can do the following with Object.assign()
:
var posts = {'2018-05-11' : {posts: 2}} // var postsvar notes = {'2018-05-11' : {notes: 1}} // var notesObject.assign(posts['2018-05-11'], notes['2018-05-11']);console.log(posts);
Here's a function that's a bit more generic. It propagates through the object and will merge into a declared variable.
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)
I hope you find this helpful.