2 回答
TA贡献1797条经验 获得超4个赞
使用以下辅助方法,遍历项目并构建所需的输出。
1) 过滤器——给定一个数组,返回为真的名称
2) hasGrandChild——给定对象是否有子对象,子对象是否有子对象。
const process = data => {
const filter = arr => arr.filter(x => x.checked).map(x => x.name);
const hasGrandChild = arr => arr.length > 0 && "children" in arr[0];
const output = {};
data.forEach(({ name, children }) => {
if (hasGrandChild(children)) {
const obj = {};
children.forEach(ch => (obj[ch.name] = filter(ch.children)));
output[name] = obj;
} else {
output[name] = filter(children);
}
});
return output;
};
var data = [
{
name: "Main Hobbies",
checked: false,
children: [
{
name: "Dance",
checked: false,
children: [
{
name: "Salsa",
checked: true
},
{
name: "Solo",
checked: false
}
]
},
{
name: "Sports",
checked: false,
children: [
{
name: "Cricket",
checked: true
}
]
}
]
},
{
name: "Game",
checked: false,
children: [
{
name: "PUBG",
checked: false
},
{
name: "Cricket",
checked: false
},
{
name: "Football",
checked: true
}
]
}
];
console.log(process(data));
TA贡献1773条经验 获得超3个赞
您可以检查子项是否不包含子项并返回一个名称数组或使用选中的节点创建一个对象。
const
getObject = array => array.every(({ children }) => !children)
? array.reduce((r, { name, checked }) => checked ? [...(r || []), name] : r, undefined)
: array.reduce((r, { name, checked, children = [] }) => {
children = getObject(children);
if (checked || children) r[name] = children;
return r;
}, {}),
data = [{ name: "Main Hobbies", checked: false, children: [{ name: "Dance", checked: false, children: [{ name: "Salsa", checked: true }, { name: "Solo", checked: false }] }, { name: "Sports", checked: false, children: [{ name: "Cricket", checked: true }] }] }, { name: "Game", checked: false, children: [{ name: "PUBG", checked: false }, { name: "Cricket", checked: false }, { name: "Football", checked: true }] }],
result = getObject(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报