FFIVE
2023-03-03 13:14:25
我想提取相同標題的對象并將所有數據添加到一個對象中。 new = [{ "data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon"}], "title": "9/9/2020", },{ "data": [{ "displayName": "Tom pvt ltd", "name": "Tom wang", }, { "displayName": "parker pvt ltd", "name": "parker wing", }], "title": "9/9/2020", }]我想要類似下面的東西:new = [{ "data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon", }, { "displayName": "Tom pvt ltd", "name": "Tom wang", }, { "displayName": "parker pvt ltd", "name": "parker wing", }], "title": "9/9/2020", }]
1 回答

忽然笑
TA貢獻1806條經驗 獲得超5個贊
您可以使用 javascript 中的Array.reduce方法對對象數組進行分組。
const objects = [{
"data": [{ "displayName": "Peter pvt ltd", "name": "Peter Zon"}],
"title": "9/9/2020",
},{
"data": [{ "displayName": "Tom pvt ltd", "name": "Tom wang", }, { "displayName": "parker pvt ltd", "name": "parker wing", }],
"title": "9/9/2020",
}]
objects.reduce((acc,curr) => {
const target = acc.find(item => curr.title === item.title);
if(target) {
target.data = [...target.data, ...curr.data];
} else {
acc.push(curr);
}
return acc;
}, []);
添加回答
舉報
0/150
提交
取消