Reputation: 25
I'm trying to filter objects in an array that contain specific values inside a property that is an array. Example, here is my array of objects:
[
{_id: 1, value: ['Row', 'Column']},
{_id: 2, value: []},
{_id: 3, value: ['Row']},
{_id: 4},
{_id: 5, value: ['Column']}
]
I need it to return all objects with 'Row' in the value array, i.e. the result should be:
[
{_id: 1, value: ['Row', 'Column']},
{_id: 3, value: ['Row']},
]
Here's my method to do this but it's returning null:
findRowValues() {
let groupObj = [
{_id: 1, value: ['Row', 'Column']},
{_id: 2, value: []},
{_id: 3, value: ['Row']},
{_id: 4},
{_id: 5, value: ['Column']}
];
return groupObj.filter(function (obj) {
return (
obj.value &&
obj.value.find(o => { o === 'Row' })
)
});
}
Upvotes: 1
Views: 69
Reputation: 11001
Use destructuring
and includes
method
function findRowValues() {
const groupObj = [
{ _id: 1, value: ["Row", "Column"] },
{ _id: 2, value: [] },
{ _id: 3, value: ["Row"] },
{ _id: 4 },
{ _id: 5, value: ["Column"] },
];
return groupObj.filter(({ value = [] }) => value.includes("Row"));
}
console.log(findRowValues())
Upvotes: 0
Reputation: 8316
That's due to the { }
inside the callback of find
. Those can be removed for implicit return or you need to use return
keyword explicity. I have used implicit return due to arrow function.
let groupObj = [
{_id: 1, value: ['Row', 'Column']},
{_id: 3, value: []},
{_id: 5, value: ['Row']},
{_id: 7},
{_id: 8, value: ['Column']}
];
function findRowValues(groupObj) {
return groupObj.filter(function (obj) {
return (
obj.value &&
obj.value.find(o => o === 'Row' )
)
});
}
console.log(findRowValues(groupObj))
For return
key word - obj.value.find(o => {return o === 'Row'} )
Upvotes: 1