• Как построить дерево из объектов в массиве JavaScrypt?

    AngReload
    @AngReload
    Кратко о себе
    function getTree(flatTree) {
    	// node["1"] is node.index
    	// node["key"] is node.parent.index
    
    	flatTree.forEach(node => {
    		const nodeIndex = node["1"];
    		const nodeParentIndex = node["key"];
    		
    		node.parent = flatTree
    			.find(someNode => someNode["1"] === nodeParentIndex);
    
    		node.childrens = flatTree
    			.filter(someNode => someNode["key"] === nodeIndex);
    
    		node.siblings = flatTree
    			.filter(someNode => someNode["key"] === nodeParentIndex && someNode !== node);
    	});
    
    	const rootNode = flatTree.find(obj => obj["1"] === 1);
    	return rootNode;
    }
    
    const flatTree = [
    	{"1": 1, "3": 128, "4": 1, "key": 0},
    	{"1": 2, "3":   0, "4": 0, "key": 1},
    	{"1": 3, "3":   0, "4": 0, "key": 1},
    	{"1": 4, "3":   0, "4": 0, "key": 2},
    	{"1": 5, "3":   0, "4": 0, "key": 2},
    	{"1": 6, "3":   0, "4": 0, "key": 3},
    	{"1": 6, "3":   0, "4": 0, "key": 3},
    	{"1": 7, "3":   0, "4": 0, "key": 1}
    ];
    
    console.log(getTree(flatTree));
    Ответ написан
    Комментировать