Merging two javascript objects into one? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

I am trying to merge the following objects into one but having no luck so far - the structure is as follows in my console.log :

    2018-05-11 : {posts: 2} // var posts     2018-05-11 : {notes: 1} // var notes 

Once merged I want it to look like the following

2018-05-11 : {posts: 2, notes: 1} 

I have tried object.assign() but it is just removing the initial posts data - what is the best approach for this?


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: