Ramda:删除嵌套结构中的对象

3
我正在尝试使用Ramda按照给定的ID删除一个对象,这是我的JSON数据格式:
{
  id: 1,
  name: "orders",
  queries: [{
    id: 120,
    name: "test1",
    queries: [{
        id: 141,
        name: "order1"
    }]
  }, {
    id: 121,
    name: "test2",
  }, {
    id: 115,
    name: "test3",
  }, {
    id: 122,
    name: "test4",
  }, {
    id: 125,
    name: "test5",
    queries: [{
        id: 126,
        name: "order2"
    }]
  }, {
    id: 143,
    name: "test6"
  }, {
    id: 144,
    name: "test7"
    queries: [{
        id: 145,
        name: "order3"
    }]
  }, {
    id: 146,
    name: "test8"
  }]
}

在上面的例子中,给定id: 141,我想在查询中删除该对象。
我尝试使用嵌套的map和filter,但似乎不起作用。有人能给一些提示吗?

请您确认一下您的 JSON 是否是有效的,并且粘贴正确的 JSON? - Karpak
1个回答

7
如果有可能要删除的id是第一个节点,最好将顶层对象包装在一个数组中。这也有助于递归解决方案。
首先,我们可以使用R.reject过滤掉具有匹配id的所有元素,以给定对象列表为例。然后,我们可以使用R.mapR.evolve对每个对象中的queries列表递归应用相同的函数。
const removeId = (id, objs) => R.map(
  R.evolve({ queries: xs => removeId(id, xs) }),
  R.reject(R.propEq('id', 141), objs)
)

你可以使用下面提供的片段,通过你的数据来查看一个示例。

const data = [{
  id: 1,
  name: "orders",
  queries: [{
    id: 120,
    name: "test1",
    queries: [{
      id: 141,
      name: "order1"
    }]
  }, {
    id: 121,
    name: "test2",
  }, {
    id: 115,
    name: "test3",
  }, {
    id: 122,
    name: "test4",
  }, {
    id: 125,
    name: "test5",
    queries: [{
      id: 126,
      name: "order2"
    }]
  }, {
    id: 143,
    name: "test6"
  }, {
    id: 144,
    name: "test7",
    queries: [{
      id: 145,
      name: "order3"
    }]
  }, {
    id: 146,
    name: "test8"
  }]
}]

const removeId = (id, objs) => R.map(
  R.evolve({ queries: xs => removeId(id, xs) }),
  R.reject(R.propEq('id', 141), objs)
)

const result = removeId(141, data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接