Learner
Learner

Reputation: 2339

How to add property to nested javascript array (of objects)?

I am trying to add a property to javascript nested array object...

I need to traverse the tree get the value of text property and convert it to lowercase and add this data as new property (lowerText)

Old array:

 var oldObject= [{
        text: "Subgroup3",
        items: [{
            text: "subgroup5",
            items: [{
                text: "subgroup6",
                items: [{
                    text: "subgroup7",
                    items: [{
                        text: "subgroup8"
                    }]
                }]
            }]
        }]
    }]

I need the new array object as below:

   var newObject= [{
        text: "Subgroup3",
        lowerText:"subgroup3",
        items: [{
            text: "subgroup5",
            lowerText:"subgroup5",
            items: [{
                text: "subgroup6",
                lowerText:"subgroup6",
                items: [{
                    text: "subgroup7",
                    lowerText:"subgroup7",
                    items: [{
                        text: "subgroup8",
                        lowerText:"subgroup8",
                    }]
                }]
            }]
        }]
    }]

This is what I tried, looping through each object and passing the items (array) to recursive function to set the property but it doesn't seem to work fine. Not sure what I am doing wrong, can someone please help me with this code?

for (var i = 0; i < data.length; i++) {
                    data[i].lowerText=data[i].text.toLowerCase();
                    loopTree(data[i].items);
                }

function loopTree(node){
 if (node) {
        $.each(node, function (idx, item) {
            item.lowerText=item.text.toLowerCase();
            if(item.items){
                loopTree(item.items)
            }
        });
    }
    }

EDIT: Below code did the job.

  for (var i = 0; i < data.length; i++) {
                    if(data[i]){
                        process( data[i]);
                    }
                }

function process(val) {
    val.lowerText = val.text.toLowerCase();  
    if(val.items){
        for(var i = 0, len = val.items.length; i < len; i++) {
            process(val.items[i]);
        }
    }
}

Upvotes: 2

Views: 6871

Answers (2)

Lloyd
Lloyd

Reputation: 29668

If you don't want to clone the objects and just modify the existing ones, try this:

function process(val) {
   val.lowerText = val.text.toLowerCase();

   for(var i = 0, len = val.items.length; i < len; i++) {
       process(val.items[i]);
   }
}

process(obj);

Upvotes: 5

hvgotcodes
hvgotcodes

Reputation: 120198

If you want to preserve the value in the old array, just push the new object onto the old array:

oldObject.push(newObject[0]);

If you just need to replace the entire array, its trivial,

oldObject = newObject;

Upvotes: -1

Related Questions