如何将Protobuf Map类型转换为预期结构的对象?
Protobuf Map 转预期对象结构(含递归嵌套处理)
针对你遇到的Protobuf toObject() 输出valuesMap数组而非预期对象结构的问题,可以编写一个递归转换函数,将所有xxxMap格式的键值对数组转换为对应xxx键名的普通对象,同时处理任意层级的嵌套结构。
递归转换函数实现
function transformProtobufObject(obj) { // 处理非对象/空值,直接返回 if (obj === null || typeof obj !== 'object') { return obj; } // 处理数组:遍历每个元素递归转换 if (Array.isArray(obj)) { return obj.map(item => transformProtobufObject(item)); } const transformed = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const value = obj[key]; // 识别xxxMap格式的键,且值为键值对数组 if (key.endsWith('Map') && Array.isArray(value)) { const targetKey = key.slice(0, -3); const mapObj = {}; // 将键值对数组转为普通对象,同时递归处理值 value.forEach(([k, v]) => { mapObj[k] = transformProtobufObject(v); }); transformed[targetKey] = mapObj; } else { // 非map字段,递归处理值后保留原键名 transformed[key] = transformProtobufObject(value); } } } return transformed; }
使用示例
// 模拟test.toObject()返回的结构 const protoOutput = { valuesMap: [ ["test", "1"], ["nestedData", { innerValuesMap: [["innerKey", "innerValue"]] }] ] }; const converted = transformProtobufObject(protoOutput); console.log(converted); // 输出结果: // { // values: { // test: "1", // nestedData: { // innerValues: { // innerKey: "innerValue" // } // } // } // }
函数特性
- 自动识别所有以
Map结尾的字段,将其对应的键值对数组转为普通对象 - 递归处理任意层级的嵌套结构(包括对象和数组中的嵌套)
- 保留非map类型的字段结构和键名不变
内容的提问来源于stack exchange,提问作者Rostislav Shtanko
相关产品推荐
相关产品推荐

