Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two javascript objects into one? [duplicate]

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?

like image 677
Zabs Avatar asked May 04 '18 13:05

Zabs


People also ask

How do you merge two arrays of objects in JavaScript and de duplicate items?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do you combine properties of two objects?

In the above example, two objects are merged into one using the Object. assign() method. The Object. assign() method returns an object by copying the values of all enumerable properties from one or more source objects.

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.


3 Answers

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.

like image 179
Atul Sharma Avatar answered Oct 26 '22 21:10

Atul Sharma


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.

like image 26
Andrew Bone Avatar answered Oct 26 '22 21:10

Andrew Bone


You can do the following with Object.assign():

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

Object.assign(posts['2018-05-11'], notes['2018-05-11']);
console.log(posts);
like image 32
Mamun Avatar answered Oct 26 '22 23:10

Mamun