Skip to content
Advertisement

How to get the length of an object after checking it is an array in Javascript

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?

Advertisement

Answer

You can use the filter method on the myObjects array

const res = myObjects.filter((object) => object.selected.length > 0 || object.selected === true )

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement