我有一个对象数组,每个对象都有一个父对象,而那个父对象有孩子。
我想有一个仅包含父母的名字和ID以及他的孩子的名字和ID的数组。以下示例显示了一个对象当前的外观。
@id: "/course_categories/1"
@type: "CourseCategory"
children: Array(5)
0: {@id: "/course_categories/2", @type: "CourseCategory", id: 2, name: "PHP voor beginners", left: 2, …}
1: {@id: "/course_categories/3", @type: "CourseCategory", id: 3, name: "PHP advanced", left: 40, …}
2: {@id: "/course_categories/4", @type: "CourseCategory", id: 4, name: "PHP voor dummies", left: 42, …}
3: {@id: "/course_categories/5", @type: "CourseCategory", id: 5, name: "PHP voor experts", left: 44, …}
4: {@id: "/course_categories/6", @type: "CourseCategory", id: 6, name: "PHP design patterns", left: 46, …}
id: 1
key: "0-1"
left: 1
level: 0
name: "PHP"
parent: null
right: 48
我想要的样子:
data: [{
title: 'PHP', id: 1, children: [
{
title: 'PHP voor beginners', id: 2, children: []
},
{
title: 'PHP advanced', id: 3, children: []
},
{
// PHP voor dummies, PHP voor experts, etc...
}
]
},
{
title: 'REACT', id: 4, children: [
{
title: 'React voor beginners', id: 5, children: [
{
title: 'React voor beginners 2', id: 6, children: []
}
]
},
{
// ....
}
]
}]
孩子也有可能拥有孩子。因此,孩子的孩子应该具有相同的格式。 (上面的示例)我知道可以通过使用递归函数来实现,但是我想知道过滤当前对象的最佳方法是什么。
答案 0 :(得分:0)
您可以使用函数通过过滤键来删除对象的属性,然后使用reduce
从剩下的键中获取对象。您可以递归调用此函数,以对子项执行相同的操作。
然后您可以编写一个单独的函数来将name
属性转换为title
:
const data = [{
"@id": "/course_categories/1",
"@type": "CourseCategory",
children: [{
"@id": "/course_categories/2",
"@type": "CourseCategory",
id: 2,
name: "PHP voor beginners",
left: 2,
},
{
"@id": "/course_categories/3",
"@type": "CourseCategory",
id: 3,
name: "PHP advanced",
left: 40,
},
{
"@id": "/course_categories/4",
"@type": "CourseCategory",
id: 4,
name: "PHP voor dummies",
left: 42,
},
{
"@id": "/course_categories/5",
"@type": "CourseCategory",
id: 5,
name: "PHP voor experts",
left: 44,
},
{
"@id": "/course_categories/6",
"@type": "CourseCategory",
id: 6,
name: "PHP design patterns",
left: 46,
}
],
id: 1,
key: "0-1",
left: 1,
level: 0,
name: "PHP",
parent: null,
right: 48,
}]
const keepProperties = (object, properties) => {
const objectWithOnlyRequiredProperties = Object.keys(object)
.filter(key => properties.indexOf(key) > -1)
.reduce((prev, curr) => ({
...prev,
[curr]: object[curr],
}), {});
const children = object.hasOwnProperty('children') ?
object.children.map(child => keepProperties(child, properties)) : [];
return {
...objectWithOnlyRequiredProperties,
children,
};
}
const transformNameToTitle = object => {
const children = object.hasOwnProperty('children') ? {
children: object.children.map(transformNameToTitle)
} : false;
const objectKeysWithoutName = Object
.keys(object)
.filter(key => key !== 'name')
const objectWithoutName = keepProperties(
object,
objectKeysWithoutName,
);
return {
...objectWithoutName,
title: object.name,
...children,
}
}
const test = transformNameToTitle(
keepProperties(data[0], ['name', 'id'])
);
console.dir(test)