'Remove all other properties from object leave only selected
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);
Solution 1:[1]
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);
Solution 2:[2]
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.
Solution 3:[3]
const objList = [
{
id: 1,
name: 'aaa',
},
{
id: 2,
name: 'bbb',
},
{
id: 3,
name: 'ccc',
},
];
var filtered = objList.filter((el) => el.id === 3 );
console.log(filtered);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3133 |
| Solution 2 | Ajeet Chauhan |
| Solution 3 | Jinal Thakkar |
