javascript - Javascript - 将对象嵌套到数组中

我尝试转换以下格式的数组:


data = [


 { name: 'Buttons/Large/Primary', id: '1:23' },


 { name: 'Buttons/Large/Secondary', id: '1:24' },


 { name: 'Buttons/Medium/Primary', id: '1:25' },


 { name: 'Buttons/Medium/Secondary', id: '1:26' },


 { name: 'Forms/Text', id: '2:1' },


 { name: 'Forms/Checkbox', id: '2:2' },


];



到此格式的数组:


data = [


 {


 name:"Buttons",


 id: '1:23',


 components: [{


 name:"Large",


 id: '1:23',


 components: [{


 name:"Primary",


 id: '1:23'


 }, {


 name:"Secondary",


 id: '1:24'


 }]


 },{


 name:"Medium",


 id: '1:25',


 components: [{


 name:"Primary",


 id: '1:25'


 }, {


 name:"Secondary",


 id: '1:26'


 }]


 }]


 }, {


 name:"Forms",


 id: '2:1',


 components: [{


 name:"Text",


 id: '2:1'


 },{


 name:"Checkbox",


 id: '2:2'


 }]


 }


];



我的方法是通过在/'/'处拆分name属性,然后从原始数据集中的每个对象创建数组,然后将它们相互嵌套。


function nestItems(obj, path, value) {


 let component = {};


 let temp = component;


 for (let i = 0; i < path.length; i++) {


 let component = temp;


 component.name = path[i];


 component.id = value;


 if (path.length - 1 === i) {



 } else {



 component.components = {};


 temp = component.components;


 }


 }


 obj.push(component)


}


let obj = [];


for (let i = 0; i < data.length; i++) {


 let path = data[i].name.split('/');


 nestItems(obj, path, data[i].id);


}


console.log(obj)



时间:

我同意你用/切分的方法。

下面是我使用reduce创建映射,并生成最终数组的方法:


const data = [


 { name: 'Buttons/Large/Primary', id: '1:23' },


 { name: 'Buttons/Large/Secondary', id: '1:24' },


 { name: 'Buttons/Medium/Primary', id: '1:25' },


 { name: 'Buttons/Medium/Secondary', id: '1:26' },


 { name: 'Forms/Text', id: '2:1' },


 { name: 'Forms/Checkbox', id: '2:2' },


];



const map = data.reduce((acc, curr) => {


 const { id } = curr;


 const [parent, sub, subSub] = curr.name.split('/');


 if (acc[parent]) {


 if (acc[parent][sub]) {


 acc[parent][sub][subSub] = { id };


 } else {


 acc[parent][sub] = { id };


 if (subSub) {


 acc[parent][sub][subSub] = { id };


 }


 }


 } else {


 acc[parent] = { id };


 if (sub && subSub) {


 acc[parent][sub] = {


 id,


 [subSub]: { id }


 };


 } else if (sub) {


 acc[parent][sub] = { id };


 };


 }



 return acc;


}, {});



const result = Object.keys(map).map(parentName => {


 const { id: parentId, ...subs } = map[parentName];


 const parentObj = { name: parentName, id: parentId };


 parentObj.components = Object.keys(subs).map(subName => {


 const { id: subId, ...subSubs } = subs[subName];


 const subObj = { name: subName, id: subId };


 if (Object.keys(subSubs).length) {


 subObj.components = Object.keys(subSubs).map(subSubName => ({ name: subSubName, id: subSubs[subSubName].id }));


 }


 return subObj;


 });



 return parentObj;


});



console.log(result);

...