【发布时间】:2021-12-26 12:33:46
【问题描述】:
我想更新这个对象数组
var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"none"}]
到
var a = [{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"},
{"uuid":"e468c4ff-98c8-4d53-986e-529e4a199540","answer":"none"},
{"uuid":"f71835b7-b57a-4971-9f0b-ff0474fd495e","answer":"none"},
{"uuid":"93161c2b-6c56-4204-b6b5-c5c3cee0f38a","answer":"found it"}]
这只会更新此数组中的第一个匹配项,但我需要它来更新所有匹配项。
a.find(x => x.uuid == "93161c2b-6c56-4204-b6b5-c5c3cee0f38a").answer = "found it"
我知道我可以遍历数组来更改与 uuid 匹配的每个答案,但是有更好的方法吗?
【问题讨论】:
-
你需要遍历数组来改变每个匹配uuid的答案。
-
如果 id 值基本上是随机顺序的,那么您所能做的就是使用循环或
.forEach()顺序搜索数组。您可以对数组进行排序,然后进行二进制搜索,或者(可能更好)将数组转换为从 uuid 值到具有“答案”值或您想要的任何其他值的容器对象(或对象数组)的映射。
标签: javascript arrays object