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

如何使用jq提取嵌套JSON指定字段并重组结构

解决方案

你可以使用数组的map方法结合对象解构来实现需求,这种方式无需逐个指定要忽略的属性,能灵活处理任意数量的额外属性:

// 假设原JSON数据已解析为JavaScript对象data
const data = {
  "items": [
    {
      "details": {
        "name": "test",
        "description": "description"
      },
      "properties": [
        {
          "property1": "someValue",
          "property2": "someOtherValue"
        }
      ],
      "additionalProperties": {
        "other": "stuff"
      }
    },
    {
      "details": {
        "name": "test2",
        "description": "description2"
      },
      "properties": [
        {
          "property1": "someValue2",
          "property2": "someOtherValue2"
        }
      ],
      "additionalProperties": {
        "other": "stuff"
      }
    }
  ]
};

// 处理数据
const processedData = {
  items: data.items.map(item => {
    // 解构出需要的details和properties,其余属性存入rest(直接忽略)
    const { details, properties, ...rest } = item;
    // 展开details的属性,再合并properties
    return { ...details, properties };
  })
};

console.log(JSON.stringify(processedData, null, 2));

代码说明

  1. 对象解构:{ details, properties, ...rest } = item 会从每个item中提取目标属性,剩下的所有额外属性会被自动收集到rest变量中,无需手动列举要忽略的属性。
  2. 对象合并:{ ...details, properties } 会把details里的所有字段(如name、description)展开,再添加properties属性,最终生成你需要的item结构。

这种逻辑完全适配你提到的"最多n个需忽略属性"的场景,不管额外属性有多少,都会被自动排除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:52:21