Convert array bên dưới sang dạng tree theo key - Javascript
Javascript convert tree - JSON
2022
interface ObjectNode {position: string;name: string;symbol: string;weight ? : number;children ? : ObjectNode[];}var exampleData = [{position: 1,name: 'Hydrogen',weight: 1.0079,symbol: 'H'}, {position: 1,name: 'Helium',weight: 4.0026,symbol: 'H'}, {position: 2,name: 'Lithium',weight: 6.941,symbol: 'L'}, {position: 3,name: 'Beryllium',weight: 9.0122,symbol: 'B'}, {position: 4,name: 'Boron',weight: 10.811,symbol: 'B'}, {position: 5,name: 'Carbon',weight: 12.0107,symbol: 'C'}, {position: 5,name: 'Nitrogen',weight: 14.0067,symbol: 'N'}, {position: 6,name: 'Oxygen',weight: 15.9994,symbol: 'O'}, {position: 7,name: 'Fluorine',weight: 18.9984,symbol: 'F'}, {position: 8,name: 'Neon',weight: 20.1797,symbol: 'N'}, ]// expect// key = ['symbol']var TREE1 = [{symbol: 'H',children: [{position: 1,name: 'Hydrogen',weight: 1.0079,symbol: 'H'}, {position: 1,name: 'Helium',weight: 4.0026,symbol: 'H'}, ]}, {symbol: 'L',children: [{position: 2,name: 'Lithium',weight: 6.941,symbol: 'L'}, ]}, ]// OR -------------------------------------------------------------------------// key = ['symbol', 'position']var TREE2 = [{symbol: 'H',children: [{position: 1,children: [{position: 1,name: 'Hydrogen',weight: 1.0079,symbol: 'H'}, {position: 1,name: 'Helium',weight: 4.0026,symbol: 'H'}, ]}]}, {symbol: 'N',children: [{position: 5,children: [{position: 5,name: 'Nitrogen',weight: 14.0067,symbol: 'N'}]}, {position: 8,children: [{position: 8,name: 'Neon',weight: 20.1797,symbol: 'N'}]}]}, ]// Cách 1var exampleField = ['symbol', 'position', 'name']function groupByFields(items: any[], fields: any[]): any[] {if (!fields.length) return items;const grField = fields[0];const keys = [...new Set(items.map(item => item[grField]))];return keys.map(key => {const fItems = items.filter(item => item[grField] === key);return {[grField]: key,children: groupByFields(fItems, fields.slice(1))}});}console.log(groupByFields(exampleData, exampleField)); // Cách 2var exampleField = ['symbol', 'position'];function buildTree(items, ...keys) {const result = [];const keySet = new Set();const groupByKey = keys.shift();items.forEach(item => {if (!keySet.has(item[groupByKey])) {keySet.add(item[groupByKey]);result.push({ [groupByKey]: item[groupByKey], children: [item] });}else {result.find((res) => res[groupByKey] === item[groupByKey]).children.push(item);}});if (keys.length) {result.forEach((res) => {res.children = buildTree(res.children, ...keys);});}return result;}console.log(new Set(['1', '1', '2', '3']));
0 nhận xét:
Post a Comment