如何通过数组JavaScript中的父键生成子键?
假设我们有一个这样的对象数组-
const arr = [ { 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' } ];
我们需要编写一个函数,该函数接受此数组并返回一个新的对象数组,每个对象都有一个额外的属性“child”,该属性必须是对象的所有id的数组,这些id是特定对象的直接或间接子对象。
因此,输出应类似于-
[ { id: 1, parent_id: 0, title: 'Movies', childs: [ 3, 5, 6 ] }, { id: 2, parent_id: 0, title: 'Music', childs: [ 4, 7, 8 ] }, { id: 3, parent_id: 1, title: 'Russian movies', childs: [ 5, 6 ] }, { id: 4, parent_id: 2, title: 'Russian music', childs: [ 7, 8 ] }, { id: 5, parent_id: 3, title: 'New', childs: [] }, { id: 6, parent_id: 3, title: 'Top10', childs: [] }, { id: 7, parent_id: 4, title: 'New', childs: [] }, { id: 8, parent_id: 4, title: 'Top10', childs: [] }, { id: 9, parent_id: 0, title: 'Soft', childs: [] } ]
现在,让我们编写此函数的代码-
示例
const arr = [ { 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' } ]; const generateChild = arr => { return arr.reduce((acc, val, ind, array) => { const childs = []; array.forEach((el, i) => { if(childs.includes(el.parent_id) || el.parent_id === val.id){ childs.push(el.id); }; }); return acc.concat({...val, childs}); }, []); }; console.log(generateChild(arr));
输出结果
控制台中的输出将为-
[ { id: 1, parent_id: 0, title: 'Movies', childs: [ 3, 5, 6 ] }, { id: 2, parent_id: 0, title: 'Music', childs: [ 4, 7, 8 ] }, { id: 3, parent_id: 1, title: 'Russian movies', childs: [ 5, 6 ] }, { id: 4, parent_id: 2, title: 'Russian music', childs: [ 7, 8 ] }, { id: 5, parent_id: 3, title: 'New', childs: [] }, { id: 6, parent_id: 3, title: 'Top10', childs: [] }, { id: 7, parent_id: 4, title: 'New', childs: [] }, { id: 8, parent_id: 4, title: 'Top10', childs: [] }, { id: 9, parent_id: 0, title: 'Soft', childs: [] } ]