javascript - 如果对象包含带有空数组的键,如何删除该对象?

标签 javascript ramda.js

我有一个对象数组。我的目标是删除包含空数组键的对象。

我正在使用 ramda,但目前遇到了困难。

const myData = {
  "one": {
    "two": {
      "id": "1",
      "three": [{
        "id": "33",
        "copy": [{
            "id": "1",
            "text": "lorem",
            "answer": [],
          },
          {
            "id": "2",
            "text": "ipsum",
            "answer": [{
              "id": 1,
              "class": "science"
            }]
          },
          {
            "id": "3",
            "text": "baesun",
            "answer": [{
              "id": 2,
              "class": "reading"
            }]
          }
        ],
      }]
    }

  }
}

flatten(pipe(
    path(['one', 'two', 'three']),
    map(step => step.copy.map(text => ({
      answers: text.answer.map(answer => ({
        class: answer.class,
      })),
    }), ), ))
  (myData))

结果是:

[{"answers": []}, {"answers": [{"class": "science"}]}, {"answers": [{"class": "reading"}]}]

这是期望:

[{"answers": [{"class": "science"}]}, {"answers": [{"class": "reading"}]}]

最佳答案

获取带有路径的内部two数组,将copy属性内的数组链接起来,并将它们投影为仅包含answer。拒绝空答案,然后改进每个答案内的对象以仅包含 class 属性。

const {pipe, path, chain, prop, project, reject, propSatisfies, isEmpty, map, evolve} = ramda

const transform = pipe(
  path(['one', 'two', 'three']), // get the array
  chain(prop('copy')), // concat the copy to a single array
  project(['answer']), // extract the answers 
  reject(propSatisfies(isEmpty, 'answer')), // remove empty answers
  map(evolve({ answer: project(['class']) })) // convert the objects inside each answer to contain only class
)

const data = {"one":{"two":{"id":"1","three":[{"id":"33","copy":[{"id":"1","text":"lorem","answer":[]},{"id":"2","text":"ipsum","answer":[{"id":1,"class":"science"}]},{"id":"3","text":"baesun","answer":[{"id":2,"class":"reading"}]}]}]}}}

const result = transform(data)

console.log(result)
<script src="//bundle.run/ramda@0.26.1"></script>

关于javascript - 如果对象包含带有空数组的键,如何删除该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55368068/

相关文章:

javascript - 使用 d3.js 计算平均 json

javascript - checkbox.attr("checked) 就像句子从句

javascript - 遍历包含不同长度数组的二维数组行

javascript - 在 Ramda 中有条件地添加和重命名属性,无需使用镜头

javascript - 从具有特定 id 的对象的数组生成新数组

javascript - 如何处理未定义的查询变量

javascript - 按钮禁用,除非两个输入字段都有值

Javascript删除合并某些属性的对象列表中的重复项

javascript - ramda js 的多级分组

javascript - 在对 javascript/NodeJS 应用程序进行原型(prototype)设计时,应该和不应该对哪些内容进行单元测试?