Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

parent child to json tree python

var arry = [{
    "parentId": null,
    "moduleId": 1

 },
 {
    "parentId": 1,
    "moduleId": 2

 },
 {
    "parentId": 1,

    "moduleId": 3

 },
 {
    "parentId": null,
    "moduleId": 4

 },
 {
    "parentId": null,
    "moduleId": 5   
 },
 {

    "parentId": 3, 
    "moduleId": 6 
 }
];

function convert(array){
    var map = {};
    for(var i = 0; i < array.length; i++){
        var obj = array[i];
        obj.children= [];

        map[obj.moduleId] = obj;

        var parent = obj.parentId || '-';
        if(!map[parent]){
            map[parent] = {
                children: []
            };
        }
        map[parent].children.push(obj);
    }
    return map['-'].children;
}

var r = convert(arry)
console.log('array', r);
console.log('result', JSON.stringify(r))
Comment

PREVIOUS NEXT
Code Example
Javascript :: this in js class method 
Javascript :: Confirm the EndingPassed--Javascript 
Javascript :: Count recurring digits in number 
Javascript :: multiple js files vuejs 
Javascript :: Remove a class when the backspace-key is pressed inside the input field 
Javascript :: buffer to base 64 online 
Javascript :: parse thymeleaf variable onclick 
Javascript :: javascript swap 
Javascript :: flatpicker not focusing in modal React 
Javascript :: i wanted to detect when a user enters an alphabet key in input text javascript 
Javascript :: js get key value from url 
Javascript :: jquery image onerror not working 
Javascript :: import lodash react 
Javascript :: javascript get each element count / occurrences / frequency from a list 
Javascript :: jquery how do i remove emoji from string 
Javascript :: empty donut chart chart js 
Javascript :: build class component react 
Javascript :: how can i use two api at the same time in angular 
Javascript :: how to write in uft-8 in write json file python 
Javascript :: how to input struct into parameter in remix 
Javascript :: how to get all words in a string that exists between two charachters using rejx js 
Javascript :: self or this javascript 
Javascript :: function for making something invisible in gdscript 
Javascript :: JavaScript call url many times 
Javascript :: how to end tsc main --watch 
Javascript :: discord.js permission bitfield 
Javascript :: what is the equivalent of cascade on delete in mongoose 
Javascript :: javascript date set day of week 
Javascript :: how we pass 2 args in switch case javascript 
Javascript :: how to use window.alert in javascript 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =