comparing one dictionary with array of dictionary

Tags: , , , ,



I want to add or remove a dictionary on the array based on two cases. For example, Let us create a array of dictionary,

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

Let us consider two cases, Case-1: An input dictionary that has both the same key and value which is in the Result variable.

input={'c':3}

then the result should be,

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

Case-2: An input dictionary that has the same key and different value(input1) and vice versa(input2) or both different key and value(input3) which the Result variable array have.

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

then the result should be,

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

Thanks in advance

Answer

You could find the index of the given key/value pair and remove this item of the array or push the object to the array.

This approach mutates the array.

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


Source: stackoverflow