我有以下格式的JSON数据,需要根据特定的值进行过滤:
[
{
"id": 0,
"name": "ROOT-0",
"childs": [
{
"id": 1,
"name": "ROOT-1",
"childs": [
{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [
{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [
{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]如果要查找ROOT-11/ROOT-12.,则需要将ROOT-1作为最终结果。
我试过使用以下代码进行过滤
var res = data[0].filter(function f(o) { if (o.name.includes("ROOT-11")) return o; })
但我无法掌握这个逻辑。有没有办法实现我想要的输出?
发布于 2018-05-12 15:40:45
你可以用find()..。
var result = data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;或者你可以写一个函数..。
function findParentName(name, data) {
return data[0].childs.find(x => {
return x.childs.find(y => {
return y.name === name;
});
}).name;
}
var result = findParentName('ROOT-11', data);
console.log(result);这样做将使您获得最佳的性能结果,因为find()将在找到匹配时立即返回,而不会像forEach()或map()那样迭代其余的每个循环。
如果你在使用ES6,你可以说.
const result = data[0].childs.find(x => x.childs.find(y => y.name === 'ROOT-11')).name;发布于 2018-05-12 15:34:54
对于任意计数嵌套的子级,可以通过迭代实际级别来使用回溯方法,如果找不到,可以使用实际名称检查子级。
如果找到想要的名称,则通过所有嵌套调用传递父名并返回。
function getParent(array, search, parent) {
return array.some(o => o.name === search || o.children && (parent = getParent(o.children, search, o.name)))
&& parent;
}
var data = [{ id: 0, name: "ROOT-0", children: [{ id: 1, name: "ROOT-1", children: [{ id: 11, name: "ROOT-11" }, { id: 12, name: "ROOT-12" }] }, { id: 2, name: "ROOT-2", children: [{ id: 21, name: "ROOT-21" }, { id: 22, name: "ROOT-22" }] }, { id: 3, name: "ROOT-3", children: [{ id: 31, name: "ROOT-31" }, { id: 32, name: "ROOT-32" }] }] }]
console.log(getParent(data, 'ROOT-0')); // undefined no parent found
console.log(getParent(data, 'ROOT-1')); // ROOT-0
console.log(getParent(data, 'ROOT-11')); // ROOT-1
console.log(getParent(data, 'ROOT-31')); // ROOT-3.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2018-05-12 15:38:12
您可以使用几个筛选器和一个查找来获取项目,以获得您想要的结果:
let items = [{
"id": 0,
"name": "ROOT-0",
"childs": [{
"id": 1,
"name": "ROOT-1",
"childs": [{
"id": 11,
"name": "ROOT-11",
},
{
"id": 12,
"name": "ROOT-12",
},
]
},
{
"id": 2,
"name": "ROOT-2",
"childs": [{
"id": 21,
"name": "ROOT-21",
},
{
"id": 22,
"name": "ROOT-22",
},
]
},
{
"id": 3,
"name": "ROOT-3",
"childs": [{
"id": 31,
"name": "ROOT-31",
},
{
"id": 32,
"name": "ROOT-32",
},
]
}
]
}]
function find(name) {
let result
items.filter(item =>
result = item.childs.find(item2 =>
item2.childs.filter(i => i.name == name).length > 0
)
)
return result.name || ''
}
console.log(find('ROOT-11'))
console.log(find('ROOT-22'))
console.log(find('ROOT-32'))
https://stackoverflow.com/questions/50307647
复制相似问题