【问题标题】:comparing one dictionary with array of dictionary将一本字典与字典数组进行比较
【发布时间】:2019-06-17 07:08:02
【问题描述】:

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

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

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

input={'c':3}

那么结果应该是,

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

案例 2: 一个输入字典,具有相同的键和不同的值(输入1),反之亦然(输入2)或结果变量数组具有不同的键和值(输入3)。​​

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

提前致谢

【问题讨论】:

  • 请提供一些代码。您已经尝试自己解决什么问题?
  • 你想改变Result吗?
  • @NinaScholz 是的,因为我是 js 新手,jquery 无法排序。帮我整理一下

标签: javascript jquery html arrays object


【解决方案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; }

【讨论】:

    【解决方案2】:

    这个问题已经得到解答,但我很享受这个任务。 这是我的工作。

    逻辑是结合Arrays,如果有key: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)

    【讨论】:

    • 谢谢,我需要更多帮助,你能给我一个单独的数组中的键和值吗@FrancisLeigh 请帮助我
    • @Venugopalsrinivasan 将stripped 数组的键和值放在自己的数组中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 2017-03-09
    相关资源
    最近更新 更多