所以我有一个有一个嵌套json数组的角组件...我想使用一种服务将这些嵌套json加载到它们自己的数组对象中,以便我可以通过ID查找。
也许有一种更好的方法,能够基于id在大型json中进行查找,但我真的不确定如何做到有角度
感谢您检查我的问题
//angular component
public nodeList = [
{name: 'production 1', id: '1' , children: [
{name: 'test one', id: '2' , children: [
{name: 'development one', id: '3' , children: []}
]},
{name: 'test two', id: '4' , children: [
{name: 'development two', id: '5' , children: []}
]}
]}
];
public nodeList2 = [
{name: 'production 2', id: '6' , children: [
{name: 'test one', id: '7' , children: [
{name: 'development three', id: '8' , children: []}
]},
{name: 'test two', id: '9' , children: [
{name: 'development four', id: '10' , children: []}
]}
]}
];
constructor (private sidenav: SideNavService) {
this.sidenav.loadNodes(this.nodeList);
this.sidenav.loadNodes(this.nodeList2);
}
//angular service
allNodes: Array<any> //maybe this should not be of type any?
//here I want to pass in lists like the one shown in the above component and parse through it a put each of the jsons into the list allNodes
loadNodes(tree) {
}
//here I want to pass in an ID and return that json, no matter how far it is nested, at this point just to get the name (the name may not be unique)
lookupNode(id: String) {
}
答案 0 :(得分:0)
您可以在这些行上使用递归方法来展平数组(更改的语法以内联方式在此处运行):
const nodeList = [
{name: 'production 1', id: '1' , children: [
{name: 'test one', id: '2' , children: [
{name: 'development one', id: '3' , children: []}
]},
{name: 'test two', id: '4' , children: [
{name: 'development two', id: '5' , children: []}
]}
]}
];
const nodeList2 = [
{name: 'production 2', id: '6' , children: [
{name: 'test one', id: '7' , children: [
{name: 'development three', id: '8' , children: []}
]},
{name: 'test two', id: '9' , children: [
{name: 'development four', id: '10' , children: []}
]}
]}
];
function flattenArr(arr){
return arr.reduce((output, obj) => {
let children = obj.children
output.push({
name: obj.name,
id: obj.id
})
if(children && children.length){
output = output.concat(flattenArr(children))
}
return output
}, [])
}
console.log(flattenArr(nodeList))
答案 1 :(得分:0)
与其进行展平,您还可以借助简单的递归遍历数组。
lookupNode(arr: Array<Object>, id: string) {
if (arr.id === id) {
return arr;
} else if (arr.children) {
for(let i = 0; i < arr.children.length; i++) {
let temp = this.lookupNode(arr.children[i], id);
if (temp !== null) {
return temp;
}
}
} else {
return null;
}
}