Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Map data within an Array in javascript

Here is my current Array looks like:

{ entity: 'A', type: 'request', requestUrl: 'val1' },
{ entity: 'A', type: 'response', responseUrl: 'val1' },
{ entity: 'B', type: 'request', requestUrl: 'val1' },
{ entity: 'B', type: 'response', responseUrl: 'val1' },
{ entity: 'C', type: 'request', requestUrl: 'val1' },
{ entity: 'C', type: 'response', responseUrl: 'val1' },
{ entity: 'D', type: 'request', requestUrl: 'val1' },
{ entity: 'D', type: 'response', responseUrl: 'val1' },
{ entity: 'DADA', type: '', responseUrl: 'val1' }

Each row contains an attribute named 'entity' which has 2 rows : one corresponding to request and other corresponding to response. I need to merge the request and response rows, and have the data as one row only. (The attribute 'type' doesn't matter in the merged row, but need to have all other attributes). So the solution would be something like:

[{"entity":"A","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"B","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"C","type":"response","requestUrl":"val1","responseUrl":"val1"},
{"entity":"D","type":"response","requestUrl":"val1","responseUrl":"val1"}]

Currently, this is what I have: https://www.w3schools.com/code/tryit.asp?filename=FUHGQN2JON75

Not sure if that's the best way to do it. Recommendations welcome on how to improve this solution.

Thanks.

like image 906
Anirudh Chhabra Avatar asked Jul 17 '26 21:07

Anirudh Chhabra


1 Answers

One option is to use reduce to group your array into an object. Use the entity as the key. Use Object.assign to convert the objects. Use Object.values to convert the object into an array.

var arr = [{"entity":"A","type":"request","requestUrl":"val1"},{"entity":"A","type":"response","responseUrl":"val1"},{"entity":"B","type":"request","requestUrl":"val1"},{"entity":"B","type":"response","responseUrl":"val1"},{"entity":"C","type":"request","requestUrl":"val1"},{"entity":"C","type":"response","responseUrl":"val1"},{"entity":"D","type":"request","requestUrl":"val1"},{"entity":"D","type":"response","responseUrl":"val1"},{"entity":"DADA","type":"","responseUrl":"val1"}];

var result = Object.values(arr.reduce((c, v) => {
  c[v.entity] = Object.assign(c[v.entity] || {}, v);
  return c;
}, {}));

console.log(result);
like image 180
Eddie Avatar answered Jul 20 '26 11:07

Eddie