嗨,也许我脑子不好或者只是累了:
但我找不到更新/操作对象数组的简单解决方案。
(没有几个循环)
我(通过每秒监听器回调)收到以下形式的状态更新:
status = {
uuid: "1065d90b-1a90",
status: "running",
data1: "xxx",
data2: "xxx", ...
}
status = {
uuid: "4075a90c-2b77",
status: "new",
data1: "xxx",
data2: "xxx", ...
}
它可能是一个新的数据集(具有新的 uniq uuid)或现有数据集的更新(现有的 uuid)
我想将它们收集在一个表中,并且需要一个以下形式的数组:
[ {uuid: "1065d90b-1a90", status: "running", data1:"xxx", ...},
{uuid: "4075a90c-2b77", status: "new", data1: "xxx", ...}, {uuid: ...} ]
我尝试过基于 uuid 作为索引的哈希列表(更好的键:值):
let allStatus[status.uuid] = status
这很有效,并且更新起来既简单又快速,但是这会产生:
{ 1065d90b-1a90: {uuid: "1065d90b-1a90", status: "running", data1:"xxx", ...},
4075a90c-2b77: {uuid: "4075a90c-2b77", status: "new", data1: "xxx", ...},
xxxxxxxx-xxxx: {uuid: ...}
}
之后我可以将完整列表复制到所需的数组形式。但我真的很想避免这种情况,因为这会每次(每秒)重新创建列表,这没什么好处,因为它用于显示 Angular 表。
如何改进和直接更新(创建)列表/数组?
最佳答案
这是一些伪代码:
- 创建一个空数组 (allStatus)
- 使用 .findIndex 检查是否存在具有该 uuid 的项目,并返回该对象在数组中的索引。
- 如果不存在具有该 uuid 的对象,则可以将该对象添加到 allStatus 数组中
- 如果存在具有该 uuid 的对象,则使用 allStatus[index] 更新该对象
这是一个代码片段,可以查看它的实际效果:
const incomingItem = {
uuid: "4075a90c-2b77",
status: "new",
data1: "yyy",
data2: "yyy",
}
const allStatus = [{
uuid: "1065d90b-1a90",
status: "running",
data1: "xxx",
data2: "xxx"
},{
uuid: "4075a90c-2b77",
status: "new",
data1: "xxx",
data2: "xxx"
}];
const index = allStatus.findIndex(item => item.uuid === incomingItem.uuid)
if (index === -1) {
// Item not in , we can add it
allStatus.push(incomingItem);
} else {
// Item is inside, we should update it
allStatus[index] = incomingItem;
}
console.log(allStatus);
在这里可以看到,incomingItem 与 allStatus 中的 item2 具有相同的 uuid,只是 data1 和 data2 不同。所以我们更新它。
您可以尝试更改传入项目的 uuid 并将其注销。 allStatus 应该包含三个项目。
现在您可以在 Angular 代码中循环遍历 allStatus。
关于javascript 对象数组通过 uuid 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51968617/