是否可以使用reduce代替此递归?基本上,如果有分组的/嵌套的行,我只想获得最小的行(非常多的行,或者如果我要用树来解释则是叶子)。
数据:
行:[
0:{group:正确,孩子:[youngest1,youngest2,youngest3]}
1:{group:false,//最新的4行数据...}
]
此代码收集[ rows[0].children[0], rows[0].children[1], rows[0].children[2], rows[1]
]
function getChildRows(rows, importRows) {
rows.forEach(row => {
if (row.group) {
importRows = getChildRows(row.children, importRows);
} else {
importRows.push(row);
}
});
return importRows;
}
这是我的尝试
function getChildRows(rows, importRows) {
return rows.reduce((accumulator, row) => {
if (row.group) {
importRows= getChildRows(row.children, accumulator);
} else {
accumulator.push(row);
}
return accumulator;
}, []);
但是我没有得到理想的结果
您可以这样做:
const rows = [
{
group: true,
name: 'row[0]',
children: [{name: 'children[0]'}, {name: 'children[1]'}, {name: 'children[2]'}]
},
{
name: 'row[1]'
}
];
function getChildRows(rows) {
return rows.reduce((acc, row) => {
return acc.concat( row.group ? getChildRows(row.children) : [row] );
}, []);
}
console.log( getChildRows(rows) );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句