[英]Remove parent JSON element depending on child value
我有一個 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"
},…
]
},…
]
},…
]
}
嵌套更深了幾個層次。 這僅顯示第一級。 我想刪除“字段”的所有元素(或更深層次的數組鍵),其中它們的“值”為空。
{
"items": [
{
"category": "login",
"fields": [
{
"label": "Password",
"value": "123456",
},
{
"label": "Website",
"fields": [
{
"label": "Name Y",
"value": "another one"
},…
]
},…
]
},…
]
}
如何在 Javascript 中執行此操作?
好吧,我找到了一種遍歷 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]);
}
}
不確定,如果它是最優雅的方式,但它到目前為止有效。
使用filter
方法,你可以得到一個過濾后的數組
它返回Boolean
。 如果value
存在,則為真
var list=JSON.parse(data)
list.items=list.items.map(val=>{
val.fields=val.fields.filter(v=>v.value})
return val
})
我們將對象掃描用於許多數據處理任務。 一旦你把頭繞在它周圍,它就會很強大。 以下是您如何回答您的問題
// 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>
免責聲明:我是對象掃描的作者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.