【发布时间】:2021-02-10 04:08:59
【问题描述】:
也许我把这个问题复杂化了……
我有几个填充了对象的数组,这些对象具有一个简单的name: numeric value 键值配对。
我想确保所有数组都包含相同的对象,并且如果它们不向数组中添加一个零值的对象。
array1 = [{'tool1': 24}]
array2 = [{'tool1': 2}, {'tool2': 21}, {'tool3': 1}]
array3 = [{'tool1': 23}, {'tool2': 13}, {'tool3': 2}, {'tool4': 10}]
array4 = [{'tool1': 18}, {'tool2': 29}, {'tool3': 19}, {'tool4': 10}]
// After the check and addition of objects, the final result of array1 and array2 would be:
array1 = [{'tool1': 24}, {'tool2': 0}, {'tool3': 0}, {'tool4': 0}]
array2 = [{'tool1': 2}, {'tool2': 21}, {'tool3': 1}, {'tool4': 0}]
// The other arrays would remain un-changed
感谢您的宝贵时间!
【问题讨论】:
-
为什么 array1 只有 3 个项目?不应该还有
tool4吗? -
@RinkeshGolwala 是的——那是我的错。已更正。
-
循环遍历所有数组,并创建一个包含所有对象键的
Set。循环遍历所有对象键和所有数组。如果数组中没有指定键的对象,则将该对象添加到数组中。 -
顺便说一句,具有不同键的对象数组使其处理起来非常复杂。为什么不把它们都放在一个对象上,比如
{tool1: 24, tool2: 13, tool3: 2}? -
一般经验法则:数组通常应该包含统一的数据。如果你有一个对象数组,它们应该包含相同的属性。
标签: javascript arrays object javascript-objects