![](/img/trans.png)
[英]Javascript: Checking object child array length even if object is not defined
[英]How to get the length of an object after checking it is an array in Javascript
我有一个对象数组,每个 object 中有一个字段可以是 boolean 或一串数组,例如
myObjects=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}, {id: "diary", selected:[]}]
我想过滤掉选择非空或真的对象。 结果将是:
result=[{id: "fruit", selected: true}, {id: "veggie", selected: ["tomato", "cucumber", "potato"]}]
这是我的代码:
for (const object in myObjects) {
if (!object[selected] || (Array.isArray(object[selected] && object[selected].length ===0)) continue
...
}
但是选择为空数组的对象不会被过滤掉。 我收到 typescript 错误
Property 'length' does not exist on type 'boolean | string[]'.
Property 'length' does not exist on type 'false'.
任何人都可以帮忙吗?
您可以在 myObjects 数组上使用 filter 方法
const res = myObjects.filter((object) => object.selected.length > 0 || object.selected === true )
你可以用循环for...of
仅当selected
属性为boolean and true
才将 object 添加到result
数组:
(typeof object.selected === "boolean" && object.selected)
或selected
属性是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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.