javascript - 如果对象包含带有空数组的键,如何删除它?
问题描述
我有一个对象数组。我的目标是删除包含空数组键的对象。
我正在使用 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"}]}]
解决方案
three
用路径获取 inside的数组,将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>
推荐阅读
- windows - 如何在命令提示符下将整个输出发送到日志文件以显示时间更改和错误
- django - Django:从管理员的静态文件夹中渲染图像
- batch-file - 使用 sed 和 bc 在文本文件中计算
- python - 如何对不同的迭代值求和?
- swift - RealmSwift:如何将多个对象添加到多对一关系?
- python - SoupStrainer 根本不提高速度
- c++ - 我的 IF 语句中的问题,Else 无法正常工作
- html-lists - QTextBrowser 显示带有多余空格的嵌套 HTML 列表
- java - 如何修复“volte_imsvt1 无法连接”错误
- python - 张量操作python中的内存和时间