I have an array of Objects called "value" in my redux store which I'm newly creating by adding start time/end time to it every time the process starts & stops. looks like this
const value = [
{startTime:1635926165, name:"dailyScripts", endTime:1635926189},
{startTime:1635926125, name:"datawarehouse", endTime:1635926125},
{startTime:1234567890, name:"dummp", endTime:1234567890}
]
I have another array of objects in a "local state" called list which has all the data. Here I want to add the start time and end time to each obj that has the same name as above.
const list = [
{pid: 248, name: 'dailyScripts', pm2_env: {…}, pm_id: 2, monit: {…}}
{pid: 259, name: 'datawarehouse', pm2_env: {…}, pm_id: 2, monit: {…}}
{pid: 0, name: 'dump', pm2_env: {…}, pm_id: 2, monit: {…}}
]
so my final output should look like this -
const list = [
{pid: 248, name: 'dailyScripts',...otherObjs, startTime:1635926165, endTime:1635926189}
{pid: 259, name: 'datawarehouse',...otherObjs, startTime:1635926125, endTime:1635926125}
{pid: 0, name: 'dump',...otherObjs, startTime:1635926165, endTime:1635926189}
]
How do I go about it with React? I want to mutate the list state or merge the value arr with the list arr.
CodePudding user response:
Try this :
const value = [
{ startTime: 1635926165, name: "dailyScripts", endTime: 1635926189 },
{ startTime: 1635926125, name: "datawarehouse", endTime: 1635926125 },
{ startTime: 1234567890, name: "dummp", endTime: 1234567890 }
];
const list = [
{ pid: 248, name: 'dailyScripts', pm2_env: {}, pm_id: 2, monit: {} },
{ pid: 259, name: 'datawarehouse', pm2_env: {}, pm_id: 2, monit: {} },
{ pid: 0, name: 'dump', pm2_env: {}, pm_id: 2, monit: {} }
];
let output = [];
list.forEach(e => {
let valueTime = value.find(ee => ee.name === e.name);
if (valueTime) {
output.push({...e, startTime : valueTime.startTime, endTime : valueTime.endTime });
} else {
output.push({...e});
}
});
console.log(output);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>