将一本字典与字典数组进行比较

时间:2019-06-17 07:08:02

标签: javascript jquery html arrays object

我想基于两种情况在数组上添加或删除字典。 例如, 让我们创建一个字典数组,

var Result=[{'a':1},{'b':2},{'c':3},{'d':4}];

让我们考虑两种情况, 情况1: 输入字典具有与Result变量相同的键和值。

input={'c':3}

那么结果应该是

 var Result=[{'a':1},{'b':2},{'d':4}];

情况2: 输入字典具有相同的键和不同的value(input1),反之亦然(input2)或Result变量数组具有不同的键和value(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}];

预先感谢

2 个答案:

答案 0 :(得分:1)

您可以找到给定键/值对的索引,然后删除数组的此项或将对象推入数组。

这种方法会改变数组。

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

答案 1 :(得分:1)

这个问题已经回答,但我很喜欢这项任务。 这是我的工作。

逻辑是将Arrayskey:value重复一起,然后忽略填充。

const INIT = [{'a':1},{'b':2},{'c':3},{'d':4}];

const input1 = {'c':3}
const input2 = {'d':6}
const input3 = {'x':3}
const input4 = {'e':10}

const INPUTS = [input1, input2, input3, input4]

const merge_and_de_dupe = (dictionary, overwrite) => {
  const combined = [...dictionary, ...overwrite]
  
  return combined.reduce((prev, curr, i, orig) => {
    const [item_key, item_value] = Object.entries(curr)[0]

    const all_duplicates = orig.filter(oI => item_key in oI && oI[item_key] === item_value)
    
    return all_duplicates.length > 1 ? prev : [...prev, curr]
  }, [])
}

const stripped = merge_and_de_dupe(INIT, INPUTS)

console.log(stripped)