如何将嵌套值对象与属性标签数组合并为指定结构的新数组
实现步骤
- 先将属性标签数组预处理为id到label的映射表,避免后续匹配时重复遍历数组,提升查询效率
- 取出
values.volume下的所有键值对,通过映射表匹配对应标签,拼装为目标结构即可
完整代码实现
const values = { volume: { length: "3", height: "4", width: "2" } } const attributes = [ { id: "notImportant", label: "notImportantFoo" }, { id: "length", label: "LengthFoo" }, { id: "width", label: "WidthFoo" }, { id: "height", label: "HeightFoo" } ] // 生成id到label的映射 const attrMap = Object.fromEntries(attributes.map(item => [item.id, item.label])) // 遍历嵌套对象生成结果 const result = Object.entries(values.volume).map(([propKey, propValue]) => ({ label: attrMap[propKey], reading: propValue }))
补充说明
- 上述代码默认输出顺序和
values.volume的属性遍历顺序一致,如果你需要和问题示例中的顺序完全匹配,可以在遍历后自行加排序逻辑,比如按label名称排序或者指定固定的属性顺序遍历 - 如果后续你的
values对象嵌套层级不固定、嵌套字段更多,可以先将嵌套对象打平为一维键值对再做匹配,打平参考代码如下:
// 递归打平嵌套对象,忽略中间层级的key,只保留最终属性key function flattenNestedObj(obj) { let res = {} for (const [key, val] of Object.entries(obj)) { if (typeof val === 'object' && val !== null && !Array.isArray(val)) { Object.assign(res, flattenNestedObj(val)) } else { res[key] = val } } return res } // 使用示例 const flatValues = flattenNestedObj(values) const result = Object.entries(flatValues).map(([k, v]) => ({ label: attrMap[k], reading: v }))
内容的提问来源于stack exchange,提问作者Louie
相关产品推荐
相关产品推荐

