Javascript对象映射,创建父子关系以形成对象



与逻辑斗争:尽我所能解释它。我有一系列的对象,比如:

[
{ categoryPath: "client/client one/client two" description: "test description"},
{ categoryPath: "client/client one" description: "test description"},
{ categoryPath: "research/research one" description: "test description"}
]

编辑:预期输出,我在预期输出中犯了一个错误。客户端一类应该有两个属性,就像在输入Object中一样,我们可以看到它的第二个对象的categoryPath是,客户端/客户端一-所以它的描述应该在客户端一层次结构下。

我需要把它转换成一个对象数组,如下所示:

[{
categoryName: 'client',
categoryId: '0',
subcategories: [
{
categoryId: '1',
categoryName: 'client one',
subcategories: [{
categoryId: '2',
categoryName: 'client two',
attributes: [
{
description: 'test description '
}],
}],
attributes: [{
description: 'test description '
},
{
description: 'test description '
}    ]
},
],
attributes: []
},
{
categoryName: 'research',
categoryId: '0',
subcategories: [
{
categoryId: '1',
categoryName: 'research one',
attributes: [
{
description: 'test description '
}],
}],
},
],
attributes: []
},

我写的代码越来越复杂,不确定你是否会得到它,但在这里:但如果你检查我的代码,它会返回循环数组问题,并在对象中嵌套父类别。

let baseObj = {
name : '',
parentName:'',
subCat: [],
att: [],
level: 0,
}
let masterObj = {};
let baseId = {};
for (let i = 0; i < arr.length; i++) {
//console.log(arr[i]);
let splitCat = arr[i].cat.split('/');
let addAttData = [...splitCat, {att:arr[i].name}];
if (!masterObj[splitCat[0]]) {
masterObj[splitCat[0]] = {...baseObj};
masterObj[splitCat[0]].name = splitCat[0];
}
getParentRec(splitCat[0], addAttData, masterObj);
}
console.log(JSON.stringify(masterObj,null,2));
Object.keys(masterObj).forEach((item, index) => {
//client//research level
console.log('new', item, masterObj[item]);
for(let i = masterObj[item].level ; i> 0; i--) {
console.log(i, 'item', masterObj[item].level);
let obj = getObj(masterObj[item]);
console.log('obj', obj);
console.log('whole fir',masterObj[item]);
obj.forEach((objItem) => {
let prName = masterObj[item][objItem].parentName;
console.log('current', masterObj[item][objItem]);
if (prName !== item) { 
let newObj = {...masterObj[item][objItem]};
masterObj[item][prName].subCat.push(newObj);
console.log('v',prName, masterObj[item][prName]);             delete masterObj[item][objItem];
console.log('after delete', masterObj[item][objItem]);
console.log('whole',masterObj[item]);
} else {
console.log('masterItem', masterObj[item]);
masterObj[item].subCat.push(masterObj[item][objItem]);
console.log(item, 'final',JSON.stringify(masterObj[item], null, 2));
}  

})
masterObj[item].level = masterObj[item].level - 1;
}
})
//console.log(JSON.stringify(masterObj, null, 2));
function getObj (obj) {
console.log(Object.keys(obj), obj.level);
let objFound= Object.keys(obj).filter(filterItem => obj[filterItem].level === obj.level);
console.log('found', obj[objFound]);
return objFound;
}
function getParentRec(parentId, arrObj, masterObj) {
//console.log('start', masterObj);
for (let i = 1; i< arrObj.length - 1 ;i++) {
let obj = {...baseObj};
//console.log('obj', obj);
let lastObj = '';
lastObj = arrObj[i];
obj.name = lastObj;
if ( i+1 === arrObj.length - 1) {
obj.att = [arrObj[arrObj.length - 1]];
}
obj.parentName = arrObj[i -1];
obj.level = i;
/* console.log('l', lastObj, i);
console.log('iobj', obj);
console.log('as ',masterObj[parentId][lastObj]); */
if (!masterObj[parentId][lastObj]) {
//console.log('wo', i);
masterObj[parentId][lastObj] = obj;
if (i >=  masterObj[parentId].level) {
masterObj[parentId].level = i;
}
//console.log('masterObj', masterObj);
}

}
return masterObj;
}

请帮助处理逻辑,它是用于创建一个文件夹展开,类似于react中的UI。因此,任何具有类似父类别的东西都会出现在该层次结构中。否则,它将形成一种新的层次结构,就像研究一样。但在客户端进入父类别的情况下,客户端会像在同级级别一样创建层次结构。

试用Array.reduce

const data = [{ categoryPath: "client/client one/client two", description: "test description"},{ categoryPath: "client/client one", description: "test description"},{ categoryPath: "research/research one", description: "test description"}];
const transforming = data.reduce((acc, {categoryPath, description}) => {
const leaf = categoryPath.split('/').reduce((parent, categoryName, index) => {
acc[categoryName] = acc[categoryName] || {
categoryId: index.toString(),
categoryName: categoryName,
subcategories: [],
attributes: []
};
if (!acc[parent].subcategories.find(child => child.categoryName === categoryName)) {
acc[parent].subcategories.push(acc[categoryName]);
}
return categoryName;
}, '-');
acc[leaf].attributes.push({description});
return acc;
}, { '-': { subcategories: [] } });
const result = transforming['-'].subcategories;
console.log(JSON.stringify(result));

编辑

const data = [{ categoryPath: "client/client one/client two", description: "test description"},{ categoryPath: "client/client one", description: "test description"},{ categoryPath: "research/research one", description: "test description"}];
const transforming = data.reduce((acc, {categoryPath, description}) => {
categoryPath.split('/').reduce((parent, categoryName, index) => {
acc[categoryName] = acc[categoryName] || {
categoryId: index.toString(),
categoryName: categoryName,
subcategories: [],
attributes: []
};
if (index > 0) {
acc[categoryName].attributes.push({description})
}
if (!acc[parent].subcategories.find(child => child.categoryName === categoryName)) {
acc[parent].subcategories.push(acc[categoryName]);
}
return categoryName;
}, '-');
return acc;
}, { '-': { subcategories: [] } });
const result = transforming['-'].subcategories;
console.log(JSON.stringify(result));

最新更新