动态钻取嵌套的对象数组

时间:2015-02-10 10:47:28

标签: javascript arrays

如何动态钻取我的对象数组?让我解释。假设我有这个带有子阵列的对象数组:

var arrOfObjects = [

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

以及知道我需要修改的层次结构中哪个数组的引用

var referenceArr = [1,0];

如何使用此引用在我的数据数组中生成正确的位置,在这种情况下,我想要到达

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

参考数组可以是任何长度,所以

var referenceArr= [0];

表示修改:

arrOfObject[0]['name'];

2 个答案:

答案 0 :(得分:2)

使用此功能:

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

答案 1 :(得分:0)

试试这个检查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)
}