Akki Akki - 7 months ago 20
Javascript Question

How to merge objects with same key in javascript?

I have a array called as

commondata


commondata = [{
giverUser: 'Abc',
createdAt: '2016 11: 48: 40',
note: 'Test'
}, {
giverUser: 'Xyz',
createdAt: '12: 22: 37',
note: 'Test data'
}, {
giverUser: 'Abc',
createdAt: '2016 14: 22: 07',
note: '"test123"'
}];


When I am trying to merge the above array of object with following code, I am getting same array as it was.

Below is my code:

commondata.forEach(function(a, i) {

if (!this[a.giverUser]) {

this[a.giveruser] = {
giverUser: a.giverUser,
createdAt: [],
note: []
};
r_grouped.push(this[a.giveruser]);
}

this[a.giveruser].createdAt = this[a.giveruser].createdAt.concat(a.createdAt);
this[a.giveruser].note = this[a.giveruser].note.concat(a.note);
}, Object.create(null));


What is wrong in above code ?
why I am not getting merger array with same giveruser ?

Answer

You have some typos with giveruser should be giverUser

Rest is working fine

var commondata = [{ giverUser: 'Abc', createdAt: '2016 11:48:40', note: 'Test' }, { giverUser: 'Xyz', createdAt: '12:22:37', note: 'Test data' }, { giverUser: 'Abc', createdAt: '2016 14:22:07', note: '"test123"' }],
    r_grouped = [];

commondata.forEach(function (a, i) {
    if (!this[a.giverUser]) {
        this[a.giverUser] = { giverUser: a.giverUser, createdAt: [], note: [] };

        r_grouped.push(this[a.giverUser]);
    }
    this[a.giverUser].createdAt.push(a.createdAt);
    this[a.giverUser].note.push(a.note);
}, Object.create(null));

document.write('<pre>' + JSON.stringify(r_grouped, 0, 4) + '</pre>');

Just another annotation

this[a.giverUser].createdAt = this[a.giverUser].createdAt.concat(a.createdAt);

this is not necessary if the value is just not an array. You can take push instead.

this[a.giverUser].createdAt.push(a.createdAt);
Comments