JavaScript忍者!现在我有这个集合:

var cats = [
    { id: 1, parent_id: 0, title: 'Movies' },
    { id: 2, parent_id: 0, title: 'Music' },
    { id: 3, parent_id: 1, title: 'Russian movies' },
    { id: 4, parent_id: 2, title: 'Russian music' },
    { id: 5, parent_id: 3, title: 'New' },
    { id: 6, parent_id: 3, title: 'Top10' },
    { id: 7, parent_id: 4, title: 'New' },
    { id: 8, parent_id: 4, title: 'Top10' },
    { id: 9, parent_id: 0, title: 'Soft' }
];


我需要这个结果:

var catsExtended = [
    { id: 1, parent_id: 0, childs: [ 3, 5, 6 ], title: 'Movies' },
    { id: 2, parent_id: 0, childs: [ 4, 7, 8 ], title: 'Music' },
    { id: 3, parent_id: 1, childs: [ 5, 6 ], title: 'Russian movies' },
    { id: 4, parent_id: 2, childs: [ 7, 8 ], title: 'Russian music' },
    { id: 5, parent_id: 3, childs: [], title: 'New' },
    { id: 6, parent_id: 3, childs: [], title: 'Top10' },
    { id: 7, parent_id: 4, childs: [], title: 'New' },
    { id: 8, parent_id: 4, childs: [], title: 'Top10' },
    { id: 9, parent_id: 0, childs: [], title: 'Soft' }
];


帮我请收集所有ID

最佳答案

您可以使用哈希表来引用已经返回的对象。对于父母,只需迭代直到parent_id为零。



var cats = [{ id: 1, parent_id: 0, title: 'Movies' }, { id: 2, parent_id: 0, title: 'Music' }, { id: 3, parent_id: 1, title: 'Russian movies' }, { id: 4, parent_id: 2, title: 'Russian music' }, { id: 5, parent_id: 3, title: 'New' }, { id: 6, parent_id: 3, title: 'Top10' }, { id: 7, parent_id: 4, title: 'New' }, { id: 8, parent_id: 4, title: 'Top10' }, { id: 9, parent_id: 0, title: 'Soft' }],
    catsExtended = cats.map(function (a) {
        var id = a.parent_id;
        this[a.id] = { id: a.id, parent_id: a.parent_id, children: [], title: a.title };
        while (id) {
            this[id].children.push(a.id);
            id = this[id].parent_id;
        }
        return this[a.id];
    }, Object.create(null));

console.log(catsExtended);

关于javascript - 如何通过数组中的父项键生成子项键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38208245/

10-13 02:29