Hi I am trying to compare two array of objects and want to achieve the custom array of object by manipulating it.
It was achieved through following
obj1 = [
{
"id":"type1",
"removed":"N",
"data":[
{
"label":"type1-a",
"removed":"N",
"dataid":12
},
{
"label":"type1-b",
"removed":"N",
"dataid":34
}
]
},
{
"id":"type2",
"removed":"N",
"data":[
{
"label":"type2-a",
"removed":"N",
"dataid":12
},
{
"label":"type2-b",
"removed":"N",
"dataid":34
}
]
}
]
obj2 = [
{
"id":"type1",
"removed":"N",
"data":[
{
"labelname":"type1-a",
"id":12
},
{
"labelname":"type1-c",
"id":34
},
{
"labelname":"type1-d",
"id":36
}
]
},
{
"id":"type2",
"removed":"N",
"data":[
{
"labelname":"type2-a",
"id":12
}
]
},
,
{
"id":"type3",
"removed":"N",
"data":[
{
"labelname":"type3-a",
"id":12
},
{
"labelname":"type3-b",
"id":34
}
]
}
]
const result = [...obj2.map(record => {
const record2 = obj1.find(pr => pr.id === record.id) || {};
const data = [...(record.data || []).map(pr => ({ ...pr,
...(record2.data.find(npr => npr.dataid === pr.id) || {})
})),
...(record2.data || []).filter(pr => !record.data.some(npr => npr.dataid === pr.id)).map(pr => ({ ...pr,
removed: 'Y'
}))
]
return {
...record,
...record2,
data
}
}), ...obj1.filter(pr => !obj2.some(npr => npr.id === pr.id)).map(pr => ({ ...pr,
removed: "Y"
}))]
console.log(result);
expected result =
[
{
"id":"type1",
"removed":"N",
"data":[
{
"label":"type1-a",
"removed":"N",
"dataid":12
},
{
"label":"type1-b",
"removed":"N",
"dataid":34
},
{
"label":"type1-d",
"dataid":36,
"removed":"N",
}
]
},
{
"id":"type2",
"removed":"N",
"data":[
{
"label":"type2-a",
"removed":"N",
"dataid":12
},
{
"label":"type2-b",
"removed":"Y",
"dataid":34
}
]
},
{
"id":"type3",
"removed":"N",
"data":[
{
"label":"type3-a",
"removed":"N",
"dataid":12
},
{
"label":"type3-b",
"removed":"N",
"dataid":34
}
]
}
]
But I am not getting the result which I am expecting.
I would like to map and modify the obj2 data if it doesn't exist in obj1.
for example, i want to modify type1,type2,type3 data object according to label, removed, and dataid instead of the newlabel and id.