嵌套数组筛选已批准用户的代码为何返回全部用户?
问题分析与解决
后端返回数据
[ { "id": 23, "who": [ { "id": 1, "user": { "id": 9, "username": "zorro", "first_name": "Richard", "last_name": "Zorro", "avatar": "http://localhost:8000/media/default.png" }, "approved": false }, { "id": 2, "user": { "id": 10, "username": "mis2", "first_name": "m", "last_name": "s", "avatar": "http://localhost:8000/media/default.png" }, "approved": true } ], "approved_looking": true, "who_add": 1 } ]
你的实现代码
filteredUsers() { if (this.users) { const filt = this.users.filter(x => x.who.filter((y) => {return y.approved === true})); return filt } },
问题原因
你在外部filter的判断条件里用了x.who.filter(...),但Array.filter()方法的返回值是数组。在JavaScript的布尔判断逻辑中,只要数组不为空就会被视为true。你的x.who数组过滤后至少会剩下一个符合条件的元素,所以这个判断永远为true,导致外部filter会保留原数组的所有元素,最终返回全部用户。
正确实现
根据需求分两种情况处理:
情况1:保留原数据结构,但仅保留who中approved为true的项
filteredUsers() { if (!this.users) return []; // 复制原数组避免修改原始数据,同时过滤who数组 return this.users.map(item => ({ ...item, who: item.who.filter(y => y.approved === true) })); },
情况2:直接提取所有approved为true的user对象
filteredUsers() { if (!this.users) return []; // 遍历所有用户组,提取符合条件的user对象 return this.users.flatMap(item => item.who.filter(y => y.approved === true).map(y => y.user) ); },
内容的提问来源于stack exchange,提问作者DoDr
相关产品推荐
相关产品推荐

