React循环并创建包含嵌套对象的新数组



我有一个文档数组:

[{
"name": "AAPL",
"ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10}
},
{
"name": "TSLA",
"ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2}
}]

和所有者数组:

{uid: "xxx"}, {uid: "yyy"}

我试图创建一个新的/(更新)所有者对象与一个嵌套的对象,其中包含他们拥有的位置。所以我想把owner更新为这样的格式:

[{uid: "xxx", "positions": [{name: "AAPL", totaledAmount: 140 },{name: "TSLA", totaledAmount: 11}] },
{uid: "yyy", "positions": [{name: "AAPL", totaledAmount: 10 },{name: "TSLA", totaledAmount: 2}] }]

实现这一点的最佳方法是什么?

我想写一些类似

的东西
owners.forEach((owner) => {
documents.forEach((document) => {
document.ownerTotals.forEach((ownerTotal) => {
if (ownerTotal.uid === owner.uid) {
}
}
})
}
})

不确定在每个循环的中心做什么,甚至不确定ForEach是否是最有效的方法…我用的是现代的react和hook。

你可以这样做:

const documents = [
{
name: "AAPL",
ownerTotals: [
{ uid: "xxx", totaledAmount: 140 },
{ uid: "yyy", totaledAmount: 10 }
]
},
{
name: "TSLA",
ownerTotals: [
{ uid: "xxx", totaledAmount: 11 },
{ uid: "yyy", totaledAmount: 2 }
]
}
];
const owners = [{ uid: "xxx" }, { uid: "yyy" }];
const res = owners.map(({ uid }) => {
let ownedDocuments = [];
documents.forEach((doc) => {
let docFound = doc.ownerTotals.find(({ uid: docUid }) => docUid === uid);
if (docFound) {
ownedDocuments.push({
name: doc.name,
totaledAmount: docFound.totaledAmount
});
}
});
return {
uid,
positions: ownedDocuments
};
});
console.log(res);

您可以使用reduce根据userid对位置进行分组。

const positions =  [{
"name": "AAPL",
"ownerTotals": {uid: "xxx", totaledAmount: 140 }, {uid: "yyy", totaledAmount: 10}
},
{
"name": "TSLA",
"ownerTotals": {uid: "xxx", totaledAmount: 11 }, {uid: "yyy", totaledAmount: 2}
}]
const posByUid = positions.reduce((acc, current) => {
const name = current.name
current.positions.forEach(position => {
if (!acc[position.uid]) {
acc[position.uid] = []
}
acc[position.uid] = {name, totaledAmount: position.totaledAmount}
})
return acc
}, {})

最新更新