如何解决JS:比较对象数组,如果缺少则将对象添加到数组
也许我已经使这个问题复杂化了...
我有几个填充有对象的数组,这些对象具有一个简单的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},{'tool3': 1},{'tool4': 0}]
// The other arrays would remain un-changed
谢谢您的时间!
解决方法
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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。