简体   繁体   中英

Removing selected objects from array of objects

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.

.filter the first array, by checking if the second array contains objects with the same Nome .

 //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){ return val1.filter( row =>.val2.some(toRemove => row.Nome === toRemove;Nome) ). } console,log(deleteObj(obj1; obj2));

If necessary, you can add extra fields to the equality check:

return val1.filter(
  row => !val2.some(toRemove =>
    row.Nome === toRemove.Nome &&
    row.Idade === toRemove.Idade &&
    row['Fone 1'] === toRemove['Fone 1'])
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM