kalabo
kalabo

Reputation: 564

jQuery Nested Array..get immediate parent id

I have the following array

array = [
{
    "id": "67",
    "sub": [
        {
            "id": "663",
        },
        {
            "id": "435",
        }
    ]
},
{
    "id": "546",
    "sub": [
        {
            "id": "23",
            "sub": [
             {
                 "id": "4",
             }
         ]
        },
        {
            "id": "71"
        }
    ]
}
]

I am currently looping throught the array as follows

calling the array:

processArray(array);

the function loop

function processArray(arr)
{
    for(var item in arr) {
        var value = arr[item];      
        var order = item;
        var itemID = value.id;

        if(itemID != null)
        {
            $('.text').append(" ORDER : " + order + " Item ID : " + itemID  + "<br />" );
        }
        if(typeof(value) == 'object') { //If it is an array,            
            processArray(arr[item]);
        }
    }   
}

Currently i am getting the order of the item and the current ID no problem. What i need however (for my database schema) is for each item get the ID of its parent if there is one. Do i need to pass the parent to each node? Or is there an easier way?

Thanks

Upvotes: 0

Views: 1558

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95578

Use an auxiliary function that has id as part of its signature:

function processArray(arr) {

    function _processArray(arr, id) {
        for (var item in arr) {

            var value = arr[item];
            var order = item;
            var itemID = value.id; // you need to change this because on the second call you pass in a string and not just an object
            var parentId = id;

            // Commenting the if statement that you had here actually shows the parent id's now.
            $('.text').append(" ORDER : " + order + " Item ID : " + itemID + " Parent Id : " + parentId + "<br />");


            if (typeof value === "object") { //use instanceof,            
                _processArray(arr[item], itemID);
            }
        }
    }

    _processArray(arr, 0);
}

Upvotes: 1

nbrooks
nbrooks

Reputation: 18233

Working demo

Include an optional parameter parentID in the function; by doing this, you can still use the processArray(array); syntax to process the original array.

function processArray(arr, parentID)
{
    for(var item in arr) {
        var value = arr[item];      
        var order = item;
        var itemID = value.id;

        if(itemID != null)
        {
            var output = " ORDER : " + order + " Item ID : " + itemID;

            if( parentID ) { output += " PARENT : " + parentID; }

            $('.text').append( output + "<br />");
        }

        // PROCESS SUB-ARRAY
        if( typeof(value.sub) == 'object') { //If it is an array,            
            processArray( value.sub, itemID );
        }
    }   
}

Upvotes: 2

Related Questions