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?
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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With