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

Javascript如何从多个结构不同的JSON中提取所有items键对应数组

嵌套JSON全层级提取items数组实现方案

需求

需要批量读取多个结构不固定的JSON文件,提取所有键为items的数组,最终整合成指定格式的结果。

输入示例

file1.json

{
   "name":"First file",
   "randomName3874":{
      "items":[
         {
            "name":"item1"
         }
      ]
   },
   "items":[
      {
         "name":"randomItem2"
      }
   ]
}

file2.json

{
   "name":"Another file",
   "randomName00000":{
      "nestedItems":{
         "items":[
            {
               "name":"item87"
            }
         ]
      }
   },
   "stuff":{
      "items":[
         {
            "name":"randomItem35"
         }
      ]
   }
}

期望输出

{
   "data":[
      {
         "items":[
            {
               "name":"item1"
            }
         ]
      },
      {
         "items":[
            {
               "name":"randomItem2"
            }
         ]
      },
      {
         "items":[
            {
               "name":"item87"
            }
         ]
      },
      {
         "items":[
            {
               "name":"randomItem35"
            }
         ]
      }
   ]
}

实现代码

核心递归提取方法

该方法不受JSON结构限制,可遍历任意嵌套层级匹配目标键:

function extractAllItems(target, result = []) {
  // 非对象/空值直接跳过
  if (typeof target !== 'object' || target === null) return result
  for (const key in target) {
    if (Object.prototype.hasOwnProperty.call(target, key)) {
      const currentValue = target[key]
      // 匹配到键为items且值为数组时加入结果
      if (key === 'items' && Array.isArray(currentValue)) {
        result.push({ items: currentValue })
      }
      // 递归遍历当前值,处理深层嵌套
      extractAllItems(currentValue, result)
    }
  }
  return result
}

Node.js环境多文件读取整合示例

const fs = require('fs/promises')
const path = require('path')

async function mergeAllItems(jsonFilePaths) {
  const finalResult = []
  for (const filePath of jsonFilePaths) {
    // 读取并解析JSON文件
    const fileRaw = await fs.readFile(filePath, 'utf-8')
    const jsonData = JSON.parse(fileRaw)
    // 提取当前文件所有匹配的items数组
    const fileMatched = extractAllItems(jsonData)
    finalResult.push(...fileMatched)
  }
  return { data: finalResult }
}

// 调用示例
const targetFiles = [
  path.resolve(__dirname, './file1.json'),
  path.resolve(__dirname, './file2.json')
]
mergeAllItems(targetFiles).then(output => {
  console.log(JSON.stringify(output, null, 2))
})

说明

  • 代码做了数组类型校验,不会匹配非数组类型的items键值
  • 可直接适配任意嵌套深度、任意结构的JSON文件,不需要提前知道文件结构
  • 浏览器环境下可直接使用extractAllItems方法处理拿到的JSON数据即可

内容的提问来源于stack exchange,提问作者Mikel Granero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:36:04