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

如何动态生成含相同UUID键与id值的feeMap结构?

完全可行,附多语言实现方案

这种需求非常常见,实现逻辑直接清晰:先生成唯一UUID,再将该UUID同时作为feeMap的键和对应子对象的id属性值即可。以下是具体实现示例:

JavaScript 实现(浏览器/Node.js 环境)

// 利用原生Crypto API生成UUID(现代环境无需依赖第三方库)
function generateUUID() {
  return crypto.randomUUID();
}

function createFeeMap(feeDataList) {
  const feeMap = {};
  feeDataList.forEach(feeInfo => {
    const uniqueId = generateUUID();
    // 同时把UUID作为键和子对象的id属性
    feeMap[uniqueId] = {
      id: uniqueId,
      ...feeInfo // 展开传入的其他费用属性,比如金额、类型等
    };
  });
  return feeMap;
}

// 使用示例
const sampleFeeData = [
  { amount: 150, type: "subscription" },
  { amount: 30, type: "handling" }
];

const myFeeMap = createFeeMap(sampleFeeData);
console.log(myFeeMap);

Python 实现

import uuid

def create_fee_map(fee_data_list):
    fee_map = {}
    for fee_info in fee_data_list:
        unique_id = str(uuid.uuid4())
        fee_map[unique_id] = {
            "id": unique_id,
            **fee_info  # 合并其他费用属性
        }
    return fee_map

# 使用示例
sample_fee_data = [
    {"amount": 200, "type": "service"},
    {"amount": 40, "type": "tax"}
]

my_fee_map = create_fee_map(sample_fee_data)
print(my_fee_map)

核心逻辑说明

  1. 通过标准UUID生成算法(如UUID v4)创建唯一标识;
  2. 将该标识同时赋值给映射表的键和子对象的id字段;
  3. 合并业务相关属性到子对象中,完成结构构建。

只要使用可靠的UUID生成方式,就能保证键与id的唯一性,完全满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:00:11