亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - js writes a recursion to restructure the data structure into another structure
天蓬老師
天蓬老師 2017-06-28 09:27:56
0
3
1080

Now we have the following data structure:

[{
    id: 1,
    pid: 0,
    name: "年級"
}, {
    id: 2,
    pid: 1,
    name: "一年級"
}, {
    id: 3,
    pid: 1,
    name: "二年級"
}, {
    id: 4,
    pid: 0,
    name: "專業(yè)"
}, {
    id: 5,
    pid: 4,
    name: "單片機開發(fā)"
}]

Write a JS method to convert it into the following format data:

[{
    id: 1,
    pid: 0,
    name: "年級",
    children: [{
        id: 2,
        pid: 1,
        name: "一年級"
    }, {
        id: 3,
        pid: 1,
        name: "二年級"
    }]
}, {
    id: 4,
    pid: 0,
    name: "專業(yè)",
    children: [{
        id: 5,
        pid: 4,
        name: "單片機開發(fā)"
    }]
}]
天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進步~~

reply all(3)
Ty80
var list = [{
    id: 1,
    pid: 0,
    name: "年級"
}, {
    id: 2,
    pid: 1,
    name: "一年級"
}, {
    id: 3,
    pid: 1,
    name: "二年級"
}, {
    id: 4,
    pid: 0,
    name: "專業(yè)"
}, {
    id: 5,
    pid: 4,
    name: "單片機開發(fā)"
}];

function parseList (list) {
    var map = {};
    list.forEach(function (item) {
        if (!map[item.id]) {
            map[item.id] = item; 
        }
    });
    list.forEach(function (item) {
        if (item.pid != 0) {
            map[item.pid].chidren ? map[item.pid].chidren.push(item) : map[item.pid].chidren = [item];
        }
    });

    return list.filter(function (item) {
        return item.pid === 0;
    });
}

var newList = parseList(list);
學(xué)習(xí)ing
var list = [
    { id: 1, pid: 0, name: "年級" },
    { id: 2, pid: 1, name: "一年級" },
    { id: 3, pid: 1, name: "二年級" },
    { id: 4, pid: 0, name: "專業(yè)" },
    { id: 5, pid: 4, name: "單片機開發(fā)" }
];

// 生成查找表,可以按 id 查到節(jié)點
const dict = list.reduce((all, item) => {
    all[item.id] = item;
    return all;
}, {});

// 由于原始數(shù)據(jù)沒有 id 為 0 的根節(jié)點,
// 這里模擬一個,最終它的 children 就是實際的所有根節(jié)點
var root = {
    id: 0
};
dict[0] = root;

// 循環(huán)添加關(guān)系
list.forEach(item => {
    const parent = dict[item.pid];
    // 確保父節(jié)點的 children 存在
    parent.children = parent.children || [];
    parent.children.push(item);
});

// 輸出結(jié)果 root.children
// 注意,root 不是結(jié)果,root.children 才是
console.log(JSON.stringify(root.children, null, 4));

某草草

Please refer to it

var sortedData = data.reduce((result, item) => {
  result[item.id] = Object.assign({}, item)
  return result
}, [])

var result = sortedData.reduce((result, item) => {
  if (item.pid === 0) {
    result.push(item)
  } else {
    if (sortedData[item.pid].children) {
      sortedData[item.pid].children.push(item)
    } else {
      sortedData[item.pid].children = [item]
    }
  }
  return result
}, [])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template