I'm trying to filter an array which contains arrays of object, based on the id. I'm able to filter them, but need to clean up the output a bit as it also returns an empty array, since the condition doesn't match for that array.
How do I fix it?
const resKey = 'ABC';
const data = [
[{
"user": {
"firstName": "John",
"lastName": "Smith",
},
"id": "ABC"
}],
[{
"user": {
"firstName": "John",
"lastName": "Smith",
},
"id": "DEF"
}]
];
const result = data.map(eachArr => eachArr.filter(eachObj => eachObj.id === resKey));
console.log(result);
Expected Output:
[
[
{
user: {
firstName: "John",
lastName: "Smith",
},
id: "ABC",
},
],
]
Actual Output:
[
[
{
user: {
firstName: "John",
lastName: "Smith",
},
id: "ABC",
},
],
[],
]
You can again filter out the empty array which doesn't contain an elements (length is 0) using filter.
.filter((arr) => arr.length);
const resKey = "ABC";
const data = [
[
{
user: {
firstName: "John",
lastName: "Smith",
},
id: "ABC",
},
],
[
{
user: {
firstName: "John",
lastName: "Smith",
},
id: "DEF",
},
],
];
const result = data
.map((eachArr) => eachArr.filter((eachObj) => eachObj.id === resKey))
.filter((arr) => arr.length);
console.log(result);