[英]Remove parent JSON element depending on child value
I have a JSON with lots of empty content:我有一个 JSON 有很多空内容:
{
"items": [
{
"category": "login",
"fields": [
{
"label": "Name",
"value": "",
},
{
"label": "E-Mail",
"value": "",
},
{
"label": "Password",
"value": "123456",
},
{
"label": "Website",
"fields": [
{
"label": "Name X",
"value": ""
},
{
"label": "Name Y",
"value": "another one"
},…
]
},…
]
},…
]
}
The nesting goes several levels deeper.嵌套更深了几个层次。 This shows only the first level.这仅显示第一级。 I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.我想删除“字段”的所有元素(或更深层次的数组键),其中它们的“值”为空。
{
"items": [
{
"category": "login",
"fields": [
{
"label": "Password",
"value": "123456",
},
{
"label": "Website",
"fields": [
{
"label": "Name Y",
"value": "another one"
},…
]
},…
]
},…
]
}
How can I do this in Javascript?如何在 Javascript 中执行此操作?
Well, I found a way to iterate through the JSON object:好吧,我找到了一种遍历 JSON object 的方法:
function remove(jsondata) {
for (let i in jsondata) {
if (jsondata[i].value != undefined && jsondata[i].value == '') {
delete jsondata[i];
}
else if (typeof jsondata[i] === "object") remove(jsondata[i]);
}
}
Not sure, if it's the most elegant way, but it works so far.不确定,如果它是最优雅的方式,但它到目前为止有效。
use filter
method,you could get a filtered array使用filter
方法,你可以得到一个过滤后的数组
it returned Boolean
.它返回Boolean
。 if value
exist,it will be true如果value
存在,则为真
var list=JSON.parse(data)
list.items=list.items.map(val=>{
val.fields=val.fields.filter(v=>v.value})
return val
})
We use object-scan for many data processing tasks.我们将对象扫描用于许多数据处理任务。 It's powerful once you wrap your head around it.一旦你把头绕在它周围,它就会很强大。 Here is how you could answer your questions以下是您如何回答您的问题
// const objectScan = require('object-scan'); const prune = (input) => objectScan(['**[*].value'], { rtn: 'count', filterFn: ({ gparent, gproperty, value }) => { if (value === '') { gparent.splice(gproperty, 1); return true; } return false; } })(input); const obj = { items: [{ category: 'login', fields: [{ label: 'Name', value: '' }, { label: 'E-Mail', value: '' }, { label: 'Password', value: '123456' }, { label: 'Website', fields: [{ label: 'Name X', value: '' }, { label: 'Name Y', value: 'another one' }] }] }] }; console.log(prune(obj)); // return count of pruned entries // => 3 console.log(obj); // => { items: [ { category: 'login', fields: [ { label: 'Password', value: '123456' }, { label: 'Website', fields: [ { label: 'Name Y', value: 'another one' } ] } ] } ] }
.as-console-wrapper {max-height: 100%;important: top: 0}
<script src="https://bundle.run/object-scan@16.0.0"></script>
Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.