javascript 由 uuid 更新的对象数组

javascript array of objects update by uuid

嗨,也许我头脑迟钝或者只是累了:
但是我找不到更新/操作对象数组的简单解决方案。 (没有几个循环)

我正在(每秒通过监听器回调)获取以下形式的状态更新:

status = {     
  uuid: "1065d90b-1a90",
  status: "running",
  data1: "xxx", 
  data2: "xxx", ...
}
status = {     
  uuid: "4075a90c-2b77",
  status: "new",
  data1: "xxx", 
  data2: "xxx", ...
}

它可能是一个新数据集(具有新的 uniq uuid)或对现有数据集的更新(现有 uuid)

我想将它们收集在 table 中,并且需要一个格式为

的数组
 [ {uuid: "1065d90b-1a90", status: "running", data1:"xxx", ...},
   {uuid: "4075a90c-2b77", status: "new", data1: "xxx", ...}, {uuid: ...} ]

我尝试了一个基于 uuid 作为索引的哈希列表(更好 key:value):

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 table。

如何改进和直接更新(创建)list/array?

这是一些伪代码:

  1. 创建一个空数组 (allStatus)
  2. 使用 .findIndex 检查数组中是否存在具有该 uuid 的项目和 return 该对象的索引。
  3. 如果不存在具有该 uuid 的对象,您可以将该对象添加到 allStatus 数组
  4. 如果存在具有该 uuid 的对象,则使用 allStatus[index]
  5. 更新该对象

这是一个代码片段,可以看到它的实际效果:

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不同。所以我们更新它。

您可以尝试更改incomingItem的uuid并注销。 allStatus 应包含三个项目。

现在您可以在 angular 代码中循环遍历 allStatus。