如何将 json 数组中的"pid"转换为"子"形式的数组?



Raw array:

const data1 = [
{
id: 1,
pid: 0
},
{
id: 2,
pid: 1
},
{
id: 3,
pid: 2
}
]

如何将 json 数组中的pid转换为children形式的数组?

如何把他变成:

[
{
id: 1,
pid: 0,
children: [
{
id: 2,
pid: 1,
children: [
{
id: 3,
pid: 2
}
]
}
]
}
]

-----------------------------------

他通过pid认出children

如何编写function来做到这一点?

谢谢

const data = [
{
id: 1,
pid: 0
},
{
id: 4,
pid: 3
},
{
id: 2,
pid: 1
},
{
id: 3,
pid: 2
}
];
function toTree (data) {
data.forEach(function(item) {
delete item.children;
});
const map = {};
data.forEach(function(item) {
map[item.id] = item;
});
let val = [];
data.forEach(function(item) {
const parent = map[item.pid];
if(parent) {
(parent.children || (parent.children = [])).push(item);
} else {
val.push(item);
}
});
return val;
}
console.log(JSON.stringify(toTree(data)));

参考@chiliNUT答案,添加一个方法:

const data1 = [
{
id: 1,
pid: 0
},
{
id: 4,
pid: 2
},
{
id: 5,
pid: 1
},
{
id: 3,
pid: 2
},
{
id: 2,
pid: 1
}
];
function toTree (data){
data.sort((a, b) => (a.pid - b.pid === 0) ? a.id - b.id : a.pid - b.pid);
const map = {}
data.forEach(item => (map[item.pid] || (map[item.pid] = []) ).push(item))
const mapArr = Object.values(map)
mapArr.reduce((a, b, index, arr) => {
if ( a[0].id === b[0].pid) { // There are still bugs here
a[0].children = b
}
return b;
})
return mapArr[0]
}
console.log(JSON.stringify(toTree(data1)));

data1.reduce((el1, el2)=>{el1.children = [el2]; return el2;});
const tree = [data1[0]];

你可以使用Array.reduce(el1, el2)它像map一样遍历数组,除了:对于第一次迭代,el1el2是数组的第一个和第二个元素,然后对于之后的迭代,el1是上一次迭代的返回值,el2是数组的下一个元素。与对数组的每个元素进行操作的 map 不同,reduce 使用数组的每个元素来生成单个返回值。

data1.reduce((el1, el2)=>{el1.children = [el2]; return el2;});

因此,这会将data1的所有元素依次附加到第一个元素。您的最终输出应该是一个数组,因此

const tree = [data1[0]]

跟进:如果数据还没有按 id 排序,可以这样排序

data1.sort((el1, el2) => {return el1.id > el2.id ? 1 : -1});

const data1 = [
{
id: 1,
pid: 0
},
{
id: 2,
pid: 1
},
{
id: 3,
pid: 2
}
]
data1.reduce((a,b)=>{a.children=[b];return b;});
const tree = [data1[0]];
console.log(tree);

我认为最好的方法是使用递归循环每个元素并作为前一个元素的子元素。

const data1 = [
{
id: 1,
pid: 0
},
{
id: 2,
pid: 1
},
{
id: 3,
pid: 2
}
];
function convert(arr){
let counter = 0;
let convertedArray = [];
function recursiveFunction(currentObject = null){
if(counter >= arr.length)   return convertedArray;
if(currentObject == null){
currentObject = {
children: [arr[0]]
}
convertedArray.push(currentObject);
} else {  
currentObject.children = [ arr[counter] ];
}

counter++;
return recursiveFunction(currentObject.children[0]);   
}
return recursiveFunction();
}

let newData = convert(data1);
console.log(newData);

最新更新