1

How can I dynamically drill down my array of objects? Let me explain. Say I have this array of objects with subarrays:

var arrOfObjects = [

    { 
        name: 'something',
        subArray: [ {
            name: 'nested something'   
        } ]
    },
    { 
        name: 'something else',
        subArray: [ {
            name: 'nested something else'   
        } ]
    }];

and a reference to know which array in the hierarchy I need to modify

var referenceArr = [1,0];

How do I use this reference to generate the proper location in my data array, in this case, I would want to get to

    arrOfObject[1]['subArray][0]['name'];
// 'subArray' and 'name' are always the same

The reference array could be any length, so

var referenceArr= [0];

indicates modifying:

arrOfObject[0]['name'];

2 Answers 2

2

Use this function:

function getValue(source, path){
    var result = source;
    while(path.length){
        result = result[path.shift()];
        if(path.length && !result.subArray)
            throw new Error('Incorrect path!');
        else if(path.length)
            result = result.subArray;
        else
            result = result.name;
    }
    return result;
}

fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Try this Check this jsfiddle

var arrOfObjects = [

    { 
        name: 'something',
        subArray: [ {
            name: 'nested something'   
        } ]
    },
    { 
        name: 'something else',
        subArray: [ {
            name: 'nested something else'   
        } ]
    }];

for(var i=0; i<arrOfObjects.length;i++){
   alert(arrOfObjects[i].subArray[0].name)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.