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

Ramda使用指南:如何为嵌套对象的子节点新增width、height属性

实现方案

你当前的场景不需要通过 lens 逐个定位节点修改,直接遍历映射所有子节点并合并属性即可,代码更简洁且易维护。

1. 仅处理根节点下第一层子节点(匹配你给出的示例结构)

// 自定义根据id生成宽高的逻辑,可按需修改
const getSizeById = (id) => ({
  width: id === 'n1' ? 100 : 200,
  height: id === 'n1' ? 50 : 80
})

const result = R.evolve({
  children: R.map(node => R.mergeLeft(getSizeById(node.id), node))
}, graph)

R.evolve会保留原对象其他属性不变,仅修改children字段,R.mergeLeft保证新增的宽高属性合并到原有节点属性中,全程immutable不会修改原始graph对象。

2. 支持深层嵌套子节点(子节点也包含children字段的场景)

如果你的结构是多层嵌套的树形结构,加一层递归逻辑即可:

// 自定义根据id生成宽高的逻辑,可按需修改
const getSizeById = (id) => ({
  width: id === 'n1' ? 100 : id === 'n2' ? 200 : 150,
  height: id === 'n1' ? 50 : id === 'n2' ? 80 : 60
})

const processNode = node => R.pipe(
  R.mergeLeft(getSizeById(node.id)),
  R.when(
    R.has('children'),
    R.evolve({ children: R.map(processNode) })
  )
)(node)

const result = processNode(graph)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:06:03