我有一个嵌套的json,其中包含带有布尔值的检查键。我只想为那些在结果数组中具有true的名称键值。
示例JSON
const treeMetaData = [
{
name : 'database',
checked : true,
schemas : [
{
name : "schema1",
checked : true,
tables : [
{
name : "table1",
checked : true,
columns : [
{
name : "column1",
checked : false,
},
{
name : "column2",
checked : true,
}
]
},
]
},
{
name : "schema2",
checked : true,
tables : [
{
name : "table2",
checked : true,
columns : [
{
name : "column4",
checked : true,
},
{
name : "column5",
checked : false,
}
]
},
]
},
]
}]
我需要的输出
["database", "schema1", "table1", "column2", "schema2", "table2", "column4"]
确实需要帮助,并希望采用优化的方法,因为此树数据的大小很大。
答案 0 :(得分:1)
似乎很简单,您是否尝试编写一些循环?
var result = [];
treeMetaData.forEach(database => {
if(!database.checked){ return; }
result.push(database.name);
database.schemas.forEach(schema => {
if(!schema.checked){ return; }
result.push(schema.name);
schema.tables.forEach(table => {
if(!table.checked){ return; }
result.push(table.name);
table.columns.forEach(column => {
if(!column.checked){ return; };
result.push(column.name);
});
});
});
});
//result is now: ["database", "schema1", "table1", "column2", "schema2", "table2", "column4"]
答案 1 :(得分:1)
您可以使用递归,并获取具有数组值的属性,以便知道要递归到的位置:
const listNames = arr =>
arr.filter(({checked}) => checked).map(obj => {
let val = Object.values(obj).find(val => Array.isArray(val));
return [obj.name].concat(val ? listNames(val) : []);
}).flat()
const treeMetaData = [{name : 'database',checked : true,schemas : [{name : "schema1",checked : true,tables : [{name : "table1",checked : true,columns : [{name : "column1",checked : false,},{name : "column2",checked : true,}]},]},{name : "schema2",checked : true,tables : [{name : "table2",checked : true,columns : [{name : "column4",checked : true,},{name : "column5",checked : false,}]},]},]}];
let res = listNames(treeMetaData);
console.log(res);
答案 2 :(得分:0)
嵌套就是答案
const treeMetaData = [
{
name : 'database',
checked : true,
schemas : [
{
name : "schema1",
checked : true,
tables : [
{
name : "table1",
checked : true,
columns : [
{
name : "column1",
checked : false,
},
{
name : "column2",
checked : true,
}
]
},
]
},
{
name : "schema2",
checked : true,
tables : [
{
name : "table2",
checked : true,
columns : [
{
name : "column4",
checked : true,
},
{
name : "column5",
checked : false,
}
]
},
]
},
]
}]
const result = []
treeMetaData.forEach(item => {
if(item['checked']){
result.push(item['name'])
let schemas = item['schemas']
schemas.forEach(schema => {
if(item['checked']){
result.push(schema['name'])
let tables = schema['tables']
tables.forEach(table => {
if(table['checked']){
result.push(table['name'])
let columns = table['columns']
columns.forEach(column => {
if(column['checked']){
result.push(column['name'])
}
});
}
});
}
});
}
});
console.log(result)