我有一个对象数组,可以将其他对象数组作为子对象(它可以具有复杂的层次结构):如果一个对象具有children
道具—如果不是,则是一个组–如果不是一个项目:
var myData = [
{
"name": "item 1"
},
{
"name": "group 1",
"children": [
{
"name": "item in a group 1"
}]
},
{
"name": "group 2",
"children": [
{
"name": "group 1 in a group 2",
"children": [
{
"name": "item in a nested group 1"
},
{
"name": "deeply nested group",
"children": [
{
"name": "deep item"
}]
},]
},
{
"name": "group 2 in a group 2",
"children": [
{
"name": "item in a nested group 2"
}]
}]
}]
我想将其解析为一个扁平的对象,该对象将所有组作为道具,并将物品作为数组,每个道具也将包括孙辈子项目。
目前,使用下面的代码,我可以展平数组,并为每个对象将组作为道具,将项目作为数组:
{
"root": [
"item 1"
],
"group 1": [
"item in a group 1"
],
"group 2": [],
"group 1 in a group 2": [
"item in a nested group 1"
],
"deeply nested group": [
"deep item"
],
"group 2 in a group 2": [
"item in a nested group 2"
]
}
但是我正在努力增加孙子孙女。这是所需的输出:
{
"root": [
"item 1"
],
"group 1": [
"item in a group 1"
],
"group 2": [
"item in a nested group 1", // includes items of child groups
"item in a nested group 2",
"deep item"
],
"group 1 in a group 2": [
"item in a nested group 1",
"deep item" // includes item of a child group
],
"deeply nested group": [
"deep item"
],
"group 2 in a group 2": [
"item in a nested group 2"
]
}
这是我正在使用的代码(我只能使用较旧版本的纯JS,因此不能使用ES6,NPM;但是可以使用polyfill)
var myItems = {
'root': []
}
var i;
for (i = 0; i < myData.length; i++)
{
parseItems(myData[i], 'root')
}
function parseItems(data, groupName)
{
var key, i;
for (key in data)
{
if (!data.hasOwnProperty(key))
continue;
else if (data.hasOwnProperty('children'))
{
groupName = data['name']
if (myItems[groupName] == undefined) myItems[groupName] = []
for (i = 0; i < data[key].length; i++)
{
parseItems(data[key][i], groupName);
}
}
else
{
myItems[groupName].push(data['name']);
}
}
}
而且我不明白如何制作此代码的版本(或者可能更好的版本),以用孙子项填充父组。
答案 0 :(得分:2)
古代版本。
function flat(array, parents, target) {
var i, j;
parents = parents || [];
target = target || { root: [] };
for (i = 0; i < array.length; i++) {
if (array[i].children) {
flat(array[i].children, parents.concat(array[i].name), target);
continue;
}
if (parents.length) {
for (j = 0; j < parents.length; j++) {
if (!target[parents[j]]) target[parents[j]] = [];
target[parents[j]].push(array[i].name);
}
} else {
target.root.push(array[i].name);
}
}
return target;
}
var data = [{ name: "item 1" }, { name: "group 1", children: [{ name: "item in a group 1" }] }, { name: "group 2", children: [{ name: "group 1 in a group 2", children: [{ name: "item in a nested group 1" }, { name: "deeply nested group", children: [{ name: "deep item" }] }] }, { name: "group 2 in a group 2", children: [{ name: "item in a nested group 2" }] }] }],
result = flat(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }