gpt4 book ai didi

javascript - 在javascript中递归压缩数组对象

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:57 27 4
gpt4 key购买 nike

我有一个对象数组,格式如下:

{
"country": "India",
"children": [
{
"name": "Karnataka",
"type": "State",
"children": [
{
"name": "",
"type": "city"
},
{
"name": "Bangalore",
"type": "city"
},
{
"name": "Mangalore",
"type": "city"
}
]
},
{
"name": "Kerala",
"type": "State",
"children": [
{
"name": "",
"type": "city"
}
]
},
{
"name": "Maharashtra",
"type": "State",
"children": [
{
"name": "Mumbai",
"type": "city"
},
{
"name": "Pune",
"type": "city"
}
]
}
]
}

每个对象都有一个包含元素详细信息的子元素。我需要递归遍历 json 对象并删除所有 name 为空字符串的节点,直到根。对于上述 json 格式,输出应如下所示:

{
"country": "India",
"children": [
{
"name": "Karnataka",
"type": "State",
"children": [
{
"name": "Bangalore",
"type": "city"
},
{
"name": "Mangalore",
"type": "city"
}
]
},
{
"name": "Kerala",
"type": "State",
"children": [
]
},
{
"name": "Maharastra",
"type": "State",
"children": [
{
"name": "Mumbai",
"type": "city"
},
{
"name": "Pune",
"type": "city"
}
]
}
]
}

如何使用 Underscorejs 在 javascript 中递归执行此操作。

最佳答案

这是 Array#filter() 的递归解决方案.

function filterName(a) {
if (a.name) {
if (Array.isArray(a.children)) {
a.children = a.children.filter(filterName);
}
return true;
}
}

var object = { "country": "India", "children": [{ "name": "Karnataka", "type": "State", "children": [{ "name": "", "type": "city" }, { "name": "Bangalore", "type": "city" }, { "name": "Mangalore", "type": "city" }] }, { "name": "Kerala", "type": "State", "children": [{ "name": "", "type": "city" }] }, { "name": "Maharashtra", "type": "State", "children": [{ "name": "Mumbai", "type": "city" }, { "name": "Pune", "type": "city" }] }] };

object.children.forEach(filterName);
document.write("<pre>" + JSON.stringify(object, 0, 4) + "</pre>");

关于javascript - 在javascript中递归压缩数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36443435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com