我想根据两种情况在数组上添加或删除字典。 例如, 让我们创建一个字典数组,
var Result=[{'a':1},{'b':2},{'c':3},{'d':4}];
让我们考虑两种情况, 情况1: 在 Result 变量中具有相同键和值的输入字典。
input={'c':3}
那么结果应该是,
var Result=[{'a':1},{'b':2},{'d':4}];
案例二: 具有相同键和不同值 (input1) 的输入字典,反之亦然 (input2) 或 Result 变量数组具有的不同键和值 (input3)。
input1={'d':6}
input2={'x':3}
input3={'e':10}
那么结果应该是,
var Result=[{'a':1},{'b':2},{'c':3},{'d':4},{'d':6},{'x':3},{'e':10}];
提前致谢
最佳答案
您可以找到给定键/值对的索引并删除数组的此项或将对象推送到数组。
这种方法会改变数组。
function update(array, object) {
var [key, value] = Object.entries(object)[0],
index = array.findIndex(o => o[key] === value);
if (index === -1) {
array.push(object);
} else {
array.splice(index, 1);
}
}
var array = [{ a: 1 }, { b: 2 }, { c: 3 }, { d: 4 }],
input1 = { c: 3 },
input2 = { d: 6 };
update(array, input1),
console.log(array);
update(array, input2);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 将一本字典与字典数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56626272/