You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 19:24:03