如何通过Array中的Parents键生成子键

时间:2016-07-05 16:21:37

标签: javascript

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' }
];

帮助我尽力收集所有身份证件

3 个答案:

答案 0 :(得分:2)

您可以使用哈希表来引用已返回的对象。并且父母只需迭代直到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);




答案 1 :(得分:1)

结合map()filter()

var catsExtended = cats.map(function(cat) {
    return {
      id: cat.id,
      parent_id: cat.parent_id,
      title: cat.title,
      childs: cats.filter(function(c) {
        return c.parent_id == cat.id;
      }).map(function(c) {
        return c.id
      })
    };
});

答案 2 :(得分:0)

我认为一个简单的Array.prototype.forEach可以做很多事情。



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' }];

cats.forEach(function(c) {
  var pid = c.parent_id;
  c.children = (this[c.id] = this[c.id] || []);
  (this[pid] = (this[pid] || [])).push(c.id)
}, Object.create(null));

console.clear();
console.log(cats);