I have an array of objects, there is one field in each object could be boolean or a string of array, for instance
myObjects=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}, {id: "diary", selected:[]}]
I would like to filter out the objects that have selected either not empty or true. The result would be:
result=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}]
Here is my code:
for (const object in myObjects) {
if (!object[selected] || (Array.isArray(object[selected] && object[selected].length ===0)) continue
...
}
But objects with selected is empty array won't get filter out. I got a typescript error
Property 'length' does not exist on type 'boolean | string[]'.
Property 'length' does not exist on type 'false'.
Can anyone help?
.filter()function. Something likemyObjects.filter(obj => (typeof obj.selected === 'boolean' && obj.selected) || obj.selected.length > 0)to filter out any boolean false or empty arraysif (!object[selected] || Array.isArray(object[selected]) && object[selected].length === 0) continueifthere's 3 opening parentheses and only 2 closing). So maybe there's something missing from the code posted here, compared to what you actually ran. It could be because instead of "continue;", you used a function or something else that is acceptable insideif(edit: I think it would only work with an operator actually). If you could clarify that, it'll probably be helpful. But yeah, what @n-- said matches with the behaviour you presented, it looks like thelengthpart is inside theisArrayfunction.object["selected"]otherwise it's looking for a variable calledselected.