I have array of arrays that contains obj, I should only take arrays that contain an obj with a specific key.
I tried to use a double filter but it doesn't work.
Can you give me some advice?
let result = [ [ { "id": 1 }, { "id": 2 } ], [ { "id": 3 }, { "id": 4 }, { "id": 5, "type": { "id": 1555 } } ], [ { "id": 6, "type": { "id": 5456 } } ] ]; const c = result.filter(array => array.filter(a => a.hasOwnProperty('type') === true)); console.log(c);
Result:
[
[
{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[
{
"id": 6,
"type": {
"id": 5456
}
}
]
]
The filter in your filter function is wrong because you don't want to return a new collection, you want to return a boolean expression. Array.some() helps and checks if any item in that subarray has this property.
let result = [ [{ "id": 1 }, { "id": 2 } ], [{ "id": 3 }, { "id": 4 }, { "id": 5, "type": { "id": 1555 } } ], [{ "id": 6, "type": { "id": 5456 } }] ]; const validArrays = result.filter(subArray => subArray.some(item => item.hasOwnProperty('type'))); console.log(validArrays);
You'll have to check whether the length of the return value from the inner array is > 0. Only if the length of the return value from the inner filter is > 0 the outer filter returns true and store it into validArrays
.
let result = [[{"id":1},{"id":2}],[{"id":3},{"id":4},{"id":5,"type":{"id":1555}}],[{"id":6,"type":{"id":5456}}]]; const validArrays = result.filter(subarray => subarray.filter(item => item.hasOwnProperty('type') === true).length > 0); console.log(validArrays);
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.