JavaScript 如何根据嵌套对象的数组属性值过滤并保留原结构
解决方案
原代码问题
- 调用
Object.values()后仅提取了属性值,过滤后返回的是数组,丢失了原对象的键结构 - 过滤逻辑错误:
tags === key是引用地址比较,且需求是校验tags数组同时包含a、b两个元素,而非匹配单个字符串
实现代码
const input1 = { "0":{ "id":"01", "name":"item_01", "tags":["a","b"], }, "1":{ "id":"02", "name":"item_02", "tags":["a","c","d"], }, "2":{ "id":"03", "name":"item_03", "tags":["a","b","f"], } } function search(input, matchTags = []) { return Object.fromEntries( Object.entries(input).filter(([_, item]) => matchTags.every(tag => item.tags?.includes(tag)) ) ) } console.log(search(input1, ["a", "b"]))
兼容低版本写法(无需Object.fromEntries)
function search(input, matchTags = []) { return Object.keys(input).reduce((result, currentKey) => { const currentItem = input[currentKey] if (matchTags.every(tag => currentItem.tags?.includes(tag))) { result[currentKey] = currentItem } return result }, {}) }
运行上述代码输出的结果与你期望的结构完全一致。
内容的提问来源于stack exchange,提问作者FS-BA
相关产品推荐
相关产品推荐

