Ramda js:用于具有嵌套对象数组的深度嵌套对象的镜头

Ramda js: lens for deeply nested objects with nested arrays of objects

本文关键字:对象 嵌套 js 深度 数组 Ramda 用于      更新时间:2023-09-26

使用 Ramda.js(和镜头),我想修改下面的 JavaScript 对象,将 ID= "/1/B/i" 的对象将 "NAME:VERSION1" 更改为 "NAME:VERSION2"。

我想使用镜头,因为我只想更改一个深度嵌套的值,但保留整个结构不变。

我不想使用 lensIndex,因为我永远不知道数组的顺序,所以相反,我想通过查找它的"id"字段来"查找"数组中的对象。

我可以用镜头来做这件事,还是应该用不同的方式做?

{
  "id": "/1",
  "groups": [
    {
      "id": "/1/A",
      "apps": [
        {
          "id": "/1/A/i",
          "more nested data skipped to simplify the example": {} 
        }
      ]
    },
    {
      "id": "/1/B",
      "apps": [
        { "id": "/1/B/n", "container": {} },
        {
          "id": "/1/B/i",
          "container": {
            "docker": {
              "image": "NAME:VERSION1",
              "otherStuff": {}
            }
          }
        }
      ]
    }
  ]
}

这应该可以通过创建一个按ID匹配对象的镜头来实现,然后可以与其他镜头组合以向下钻取到图像字段。

首先,我们可以创建一个镜头,该镜头将专注于与某个谓词匹配的数组元素(注意:仅当保证与列表中的至少一个元素匹配时,这将是一个有效的镜头)

//:: (a -> Boolean) -> Lens [a] a
const lensMatching = pred => (toF => entities => {
    const index = R.findIndex(pred, entities);
    return R.map(entity => R.update(index, entity, entities),
                 toF(entities[index]));
});

请注意,我们在此处手动构建镜头,而不是使用 R.lens 来节省查找与谓词匹配的项目索引的重复。

一旦我们有了这个函数,我们就可以构建一个与给定ID匹配的镜头。

//:: String -> Lens [{ id: String }] { id: String }
const lensById = R.compose(lensMatching, R.propEq('id'))

然后我们可以将所有镜头组合在一起以针对图像领域

const imageLens = R.compose(
  R.lensProp('groups'),
  lensById('/1/B'),
  R.lensProp('apps'),
  lensById('/1/B/i'),
  R.lensPath(['container', 'docker', 'image'])
)

可用于更新data对象,如下所示:

set(imageLens, 'NAME:VERSION2', data)

然后,如果需要,可以更进一步,并声明一个专注于图像字符串版本的镜头。

const vLens = R.lens(
  R.compose(R.nth(1), R.split(':')),
  (version, str) => R.replace(/:.*/, ':' + version, str)
)
set(vLens, 'v2', 'NAME:v1') // 'NAME:v2'

然后,可以将其附加到imageLens的组合中,以针对整个对象中的版本。

const verLens = compose(imageLens, vLens);
set(verLens, 'VERSION2', data);

这是一个解决方案:

const updateDockerImageName =
R.over(R.lensProp('groups'),
       R.map(R.over(R.lensProp('apps'),
                    R.map(R.when(R.propEq('id', '/1/B/i'),
                                 R.over(R.lensPath(['container', 'docker', 'image']),
                                        R.replace(/^NAME:VERSION1$/, 'NAME:VERSION2')))))));

当然,这可以分解为更小的函数。 :)