Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two array of objects in Javascript

I have two array of objects:

let genericObj = [{"name": "success", }, {"name": "failure"}, {"name":"timeout"}, {"name": "max"}, {"name": "min"}, {"name": "avg"}]
let x = [
    { y: 14037 },
    { y: 0 },
    { y: 0 },
    { y: 1.1960000000000002 },
    { y: 0.089 },
    { y: 0.18 }
  ];

I want to merge the two so I have an array of object

let finalObj= [{"name": "success", y: 23432}, {"name": "fail", y: 23423}] etc

I have tried a few things but it's not working for me.

like image 592
sharsart Avatar asked Dec 02 '22 09:12

sharsart


1 Answers

You could take the arrays in an array and merge the objects by index.

This approach works for any count of arrays.

let genericObj = [{"name": "success", }, {"name": "failure"}, {"name":"timeout"}, {"name": "max"}, {"name": "min"}, {"name": "avg"}],
    x = [{ y: 14037 }, { y: 0 }, { y: 0 }, { y: 1.1960000000000002 }, { y: 0.089 }, { y: 0.18 }],
    result = [genericObj, x].reduce((a, b) => a.map((o, i) => ({ ...o, ...b[i] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 145
Nina Scholz Avatar answered Dec 20 '22 13:12

Nina Scholz