4

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 ?

5
  • You could use reduce and object.assign. Commented Apr 27, 2016 at 15:14
  • Your answer is already in here. stackoverflow.com/questions/171251/… Commented Apr 27, 2016 at 15:15
  • oh but what's wrong in above code ? Commented Apr 27, 2016 at 15:16
  • @DININDU : my code has single array of object and not two different objects..please see carefully! Commented Apr 27, 2016 at 15:19
  • @Akki developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Apr 27, 2016 at 15:20

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.