I want to add or remove a dictionary on the array based on two cases. For example, Let us create a array of dictionary,
JavaScript
x
2
1
var Result=[{'a':1},{'b':2},{'c':3},{'d':4}];
2
Let us consider two cases, Case-1: An input dictionary that has both the same key and value which is in the Result variable.
JavaScript
1
2
1
input={'c':3}
2
then the result should be,
JavaScript
1
2
1
var Result=[{'a':1},{'b':2},{'d':4}];
2
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.
JavaScript
1
4
1
input1={'d':6}
2
input2={'x':3}
3
input3={'e':10}
4
then the result should be,
JavaScript
1
2
1
var Result=[{'a':1},{'b':2},{'c':3},{'d':4},{'d':6},{'x':3},{'e':10}];
2
Thanks in advance
Advertisement
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.
JavaScript
1
20
20
1
function update(array, object) {
2
var [key, value] = Object.entries(object)[0],
3
index = array.findIndex(o => o[key] === value);
4
5
if (index === -1) {
6
array.push(object);
7
} else {
8
array.splice(index, 1);
9
}
10
}
11
12
var array = [{ a: 1 }, { b: 2 }, { c: 3 }, { d: 4 }],
13
input1 = { c: 3 },
14
input2 = { d: 6 };
15
16
update(array, input1),
17
console.log(array);
18
19
update(array, input2);
20
console.log(array);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }