What I'm doing wrong when I try to get some objects into an array of objects based in another array of objects (that is result of selection of user):
//Original array
let obj1 = [
{"Nome": "João", "Idade": 16, "Fone 1": "55 5555"},
{"Nome": "Pedro", "Idade": 16, "Fone 1": "55 5555"},
{"Nome": "Marcos", "Idade": 16, "Fone 1": "55 5555"},
{"Nome": "Lucas", "Idade": 16, "Fone 1": "55 5555"},
{"Nome": "Tiago", "Idade": 16, "Fone 1": "55 5555"}
];
//Array selected by the user to delete:
let obj2 = [
{"Nome": "Marcos", "Idade": 16, "Fone 1": "55 5555"},
{"Nome": "Lucas", "Idade": 16, "Fone 1": "55 5555"},
];
function deleteObj(val1, val2){
let val = [];
for (const i of val1) {
for (const x of val2) {
JSON.stringify(i) !== JSON.stringify(x) ? val.push(i) : {};
}
}
return val;
}
console.log(deleteObj(obj1, obj2));
I'll use this code to remove the values selected by the user in the JSON file, but, when I run the result is:
[
{ Nome: 'João', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'João', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Pedro', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Pedro', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Marcos', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Lucas', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Tiago', Idade: 16, 'Fone 1': '55 5555' },
{ Nome: 'Tiago', Idade: 16, 'Fone 1': '55 5555' }
]
Seems that the "non-selected" values are added too.