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

如何将id列表映射到对象列表:为每个水果对象绑定对应id

如何将ids列表依次绑定到对应的Fruit对象中?

需求概述

把输入数据里ids数组的每个id,按顺序绑定到request.Fruits.item数组中对应的fruit对象内,最终返回包含绑定后对象的指定结构。

输入数据

{
  "ids": ["1", "2", "3"],
  "request": {
    "Fruits": {
      "item": [
        {
          "fruit": {
            "Type": "fruit",
            "name": "apple"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "banana"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "orange"
          }
        }
      ]
    }
  }
}

预期输出

{
  "request": {
    "Fruits": {
      "item": [
        {
          "fruit": {
            "Type": "fruit",
            "name": "apple",
            "id": "1"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "banana",
            "id": "2"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "orange",
            "id": "3"
          }
        }
      ]
    }
  }
}

实现方案(JavaScript)

通过遍历item数组,将对应索引的id赋值给每个fruit对象:

function bindIdsToFruits(inputData) {
  // 深拷贝原数据,避免修改原始对象
  const result = JSON.parse(JSON.stringify(inputData));
  
  // 遍历item数组,按索引匹配绑定id
  result.request.Fruits.item.forEach((item, index) => {
    if (inputData.ids[index]) {
      item.fruit.id = inputData.ids[index];
    }
  });
  
  // 移除ids字段,返回目标结构
  delete result.ids;
  return result;
}

// 示例调用
const input = {
  "ids": ["1", "2", "3"],
  "request": {
    "Fruits": {
      "item": [
        {"fruit": {"Type": "fruit", "name": "apple"}},
        {"fruit": {"Type": "fruit", "name": "banana"}},
        {"fruit": {"Type": "fruit", "name": "orange"}}
      ]
    }
  }
};

const output = bindIdsToFruits(input);
console.log(JSON.stringify(output, null, 2));

说明

  1. 先对输入数据做深拷贝,防止操作过程中污染原始数据;
  2. 利用数组索引一一匹配ids和item中的元素,给每个fruit对象添加id属性;
  3. 删除结果中的ids字段,输出符合要求的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 07:48:28