在嵌套数组中查找空数组并在Javascript中删除它们
我有一个嵌套的层次化对象数组,如下所示在嵌套数组中查找空数组并在Javascript中删除它们,javascript,Javascript,我有一个嵌套的层次化对象数组,如下所示 [{ "id": 0, "name": "E00-E90 Stoffwechselstörungen", "parentId": null, "children": [{ "id": 1, "name": "E70-E90 Stoffwechselstörungen", &q
[{
"id": 0,
"name": "E00-E90 Stoffwechselstörungen",
"parentId": null,
"children": [{
"id": 1,
"name": "E70-E90 Stoffwechselstörungen",
"parentId": 0,
"children": [{
"id": 2,
"name": "E70.- Störungen des Stoffwechsels aromatischer Aminosäuren",
"parentId": 1,
"children": []
}, {
"id": 3,
"name": "E71.- Störungen des Stoffwechsels verzweigter Aminosäuren und des Fettsäurestoffwechsels",
"parentId": 1,
"children": []
}, {
"id": 4,
"name": "E72.- Sonstige Störungen des Aminosäurestoffwechsels",
"parentId": 1,
"children": []
},
...
现在我想从最后一个子数组中删除空数组“children”:[]
我用reduce
试过了,但没有任何错误
var lastElementLength = list.length - 1
const findItemNested = (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
const resEmptyChildren = findItemNested(roots, lastElementLength, "children");
console.log('resEmptyChildren', resEmptyChildren)
您可以使用递归来实现这一点
var tInput=[{
“id”:0,
“名称”:“E00-E90 Stoffwechselstörungen”,
“parentId”:空,
“儿童”:[{
“id”:1,
“名称”:“E70-E90 Stoffwechselstörungen”,
“parentId”:0,
“儿童”:[{
“id”:2,
“名称”:“E70.-Störungen des Stoffwechsels Aromoischer Aminosäuren”,
“家长ID”:1,
“儿童”:[]
}, {
“id”:3,
“名称”:“E71.-Störungen des Stoffwechsels verzweigter Aminosäuren and des Fettsäurestoffwechsels”,
“家长ID”:1,
“儿童”:[]
}, {
“id”:4,
“名称”:“E72.-Sonstige Störungen des Aminosäurestoffwechsels”,
“家长ID”:1,
“儿童”:[]
}]
}]
}];
(函数removeEmptyChildrenProperties(输入){
log('Checking id:',input.id');
if(input.hasOwnProperty('children')){
if(input.children&&input.children.length){
input.children.forEach(removeMptyChildrenProperties)
}
否则{
log('Remove-children-on-id:',input.id');
删除input.children
}
};
返回输入
}).应用(空,tInput);
log(JSON.stringify(tInput))代码>“没有任何错误就无法工作”-您不认为知道您会遇到什么错误可能会很有趣吗?代码中的“根”和“列表”是什么?列表是对象的平面数组,而根是分层版本