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

如何动态更新含多键值对的对象并构建目标JSON响应

动态匹配JSON结构与值的实现方案

问题描述

我有两个动态JSON输入:

  1. Input 1(结构模板):定义最终响应的分组结构,分组数量、分组内字段数量均可动态变化,部分分组也可能不存在,示例如下:
{
   "Chats": {
       "customerContact": "",
       "reply": ""
   },
   "Service": {
       "history": ""
   },
   "Home": {
       "display": ""
   },
   "Recommendation": {
       "chatBot": "",
       "promotion": ""
   }
}
  1. Input 2(字段值集合):是包含所有字段键值对的对象数组(示例为单个对象),键值对总数与Input 1的字段总数完全匹配,示例如下:
[{
    "customerContact": true,
    "reply": false,
    "history": "not available",
    "display": "144 Hz",
    "chatBot": "France",
    "promotion": true
}]

需要将Input 2中的值填充到Input 1对应的结构中,生成目标JSON:

{
   "Chats": {
       "customerContact": true,
       "reply": false
   },
   "Service": {
       "history": "not available"
   },
   "Home": {
       "display": "144 Hz"
   },
   "Recommendation": {
       "chatBot": "France",
       "promotion": true
   }
}

实现思路与代码示例

核心逻辑是遍历Input 1的分组及分组内字段,从Input 2的对象中取出对应键的值填充到结构中。以下是JavaScript实现代码:

function fillStructure(template, valuesArray) {
    const values = valuesArray[0];
    const result = {};
    
    // 遍历模板的每个分组
    for (const [groupKey, fields] of Object.entries(template)) {
        result[groupKey] = {};
        // 遍历分组下的每个字段,填充对应值
        for (const fieldKey of Object.keys(fields)) {
            result[groupKey][fieldKey] = values[fieldKey];
        }
    }
    
    return result;
}

// 示例调用
const input1 = {
   "Chats": {
       "customerContact": "",
       "reply": ""
   },
   "Service": {
       "history": ""
   },
   "Home": {
       "display": ""
   },
   "Recommendation": {
       "chatBot": "",
       "promotion": ""
   }
};

const input2 = [{
    "customerContact": true,
    "reply": false,
    "history": "not available",
    "display": "144 Hz",
    "chatBot": "France",
    "promotion": true
}];

const targetJson = fillStructure(input1, input2);
console.log(JSON.stringify(targetJson, null, 2));

关键说明

  • 方案完全适配动态结构:无论Input 1的分组数量、分组内字段数量如何变化,只要Input 2的键值对总数与Input 1的字段总数一致,就能正确填充。
  • 若Input 2数组包含多个对象,可循环处理每个对象,生成多个目标结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:57:35