I have an array of objects, there is one field in each object could be boolean or a string of array, for instance
JavaScript
x
2
1
myObjects=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}, {id: "diary", selected:[]}]
2
I would like to filter out the objects that have selected either not empty or true. The result would be:
JavaScript
1
2
1
result=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}]
2
Here is my code:
JavaScript
1
5
1
for (const object in myObjects) {
2
if (!object[selected] || (Array.isArray(object[selected] && object[selected].length ===0)) continue
3
4
}
5
But objects with selected is empty array won’t get filter out. I got a typescript error
JavaScript
1
3
1
Property 'length' does not exist on type 'boolean | string[]'.
2
Property 'length' does not exist on type 'false'.
3
Can anyone help?
Advertisement
Answer
You can use the filter method on the myObjects array
JavaScript
1
3
1
const res = myObjects.filter((object) => object.selected.length > 0 || object.selected === true )
2
3