1

How can I group JSON Array by multiple Keys in Nodejs.

Is there any solution with underscore or lodash (does not matter if its plain javascript)?

Array:

[{ key: '2017-1', y: 1, gkey: 'y' },
{ key: '2017-1', x: 1, gkey: 'x' }]

Expected Result :

[{ key: '2017-1', x: 1, y:1 }]
2
  • please show your attempt Commented Apr 27, 2018 at 16:42
  • usnig deepmerge, merge.all(r); r is the Array. Commented Apr 27, 2018 at 16:45

2 Answers 2

1

You can use reduce and Object.values

let arr = [ 
   { key: '2017-1', y: 1, gkey: 'y' },
   { key: '2017-1', x: 1, gkey: 'x' },
   { key: '2017-2', x: 1, gkey: 'x' },
];

let result = Object.values(arr.reduce((c, {key,gkey,...r}) => {
  c[key] = c[key] || {key};
  c[key] = Object.assign(c[key], r);
  return c;
}, {}));

console.log(result);

If you cant use Object.values on your nodejs version, you can:

let arr = [ 
   { key: '2017-1', y: 1, gkey: 'y' },
   { key: '2017-1', x: 1, gkey: 'x' },
   { key: '2017-2', x: 1, gkey: 'x' },
];

let temp = arr.reduce((c, {key,gkey,...r}) => {
  c[key] = c[key] || {key};
  c[key] = Object.assign(c[key], r);
  return c;
}, {});

let result = [];
for (let key in temp) result.push(temp[key]);

console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

Happy to help @JamalAbo
What do you recommend? First or second
If the first one is working with the version of your nodejs, then I recomend the first one :)
1

if I understood correctly what you need, the reduce function could do what you need.

reduce call the function for each element of the array. arr is the result array who will be return by the reduce at the end. I check for each elem if it's in the arr. if not, I add it.

I did not test this code, but it should work

arrayOfData.reduce((arr, elem) => {
    let e = arr.find(el => el.key === elem.key);
    if(!e) {
        e = {key : elem.key}
        arr.push(e);
    }
    e[elem.gkey] = elem[elem.gkey];
    return arr;
}, [])

2 Comments

Its working for 2 keys only!, how can i add another key without any changes like, {key:"2017-1", x:1,y:1,t:1}
what do you mean? if I have : [{key : '2017-1', x : 1, gkey : 'x'}, {key : '2017-1', y : 1, gkey : 'y'}, {key : '2017-1', t : 1, gkey : 't'}] it give me : {key:"2017-1", x:1,y:1,t:1}

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.