I need to remove all array members that are not based on property given, here is example I have something like this
const idToStay = 1;
const objList = [{
id: 1,
name: 'aaa',
},
{
id: 4,
name: 'bbb',
},
{
id: 7,
name: 'ccc',
},
];
I need to remove all others objects that does not have id with number 1, I know how to remove but how to stay and remove all others
Here I can remove like this
const filteredObjList = objList.filter(x => !idsToRemove.includes(x.id));
console.log(filteredObjList);
CodePudding user response:
It's the same thing, just without the exclamation mark
const idToStay = 1;
const objList = [{
id: 1,
name: 'aaa',
},
{
id: 4,
name: 'bbb',
},
{
id: 7,
name: 'ccc',
},
];
const filteredObjList = objList.filter(x => idToStay === x.id);
console.log(filteredObjList);
CodePudding user response:
I hope this works for you.
var filtered = objList.filter(function(el) { return el.id === 1; });
console.log(filtered);
Thanks, Mark it as answer if it works.