【问题标题】:JS: Compare array of objects and add object to array if missingJS:比较对象数组并在缺少时将对象添加到数组中
【发布时间】: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


【解决方案1】:

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}]


function myFunc(arr) {
    for (let i = 1; i <= 4; i++) {
        if (!arr.find(element => element['tool' + i])) {
            let obj = {};
            obj['tool' + i] = 0;
            arr.push(obj);
        }
    }
}

myFunc(array1)
console.log('array1: ' + JSON.stringify(array1));
myFunc(array2)
console.log('array2: ' + JSON.stringify(array2));
myFunc(array3)
console.log('array3: ' + JSON.stringify(array3));
myFunc(array4)
console.log('array4: ' + JSON.stringify(array4));

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 2017-03-04
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2019-01-04
    • 2021-06-15
    相关资源
    最近更新 更多