Reputation: 3685
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?
Upvotes: 0
Views: 114
Reputation: 9243
You could do it with loop for...of
add object to result
array only if selected
property is boolean and true
:
(typeof object.selected === "boolean" && object.selected)
or selected
property is an array and have elements
:
(Array.isArray(object["selected"]) && object["selected"].length !== 0)
const myObjects = [{
id: "fruit",
selected: true,
},
{
id: "veggie",
selected: ["tomato", "cucumber", "potato"],
},
{
id: "diary",
selected: [],
},
];
let result = [];
// vv replace 'in' with 'of' since you loop over an array not an object
for (const object of myObjects) {
if (
(typeof object.selected === "boolean" && object.selected) ||
(Array.isArray(object["selected"]) && object["selected"].length !== 0)
)
result.push(object);
}
console.log(result);
Upvotes: 0
Reputation: 1456
You can use the filter method on the myObjects array
const res = myObjects.filter((object) => object.selected.length > 0 || object.selected === true )
Upvotes: 3