I'm trying to write a recursive function which returns the correct nested object within my model, based on an array of indexes.
My console log labelled 'inside function' actually shows the correct obj! Which is baffling me as all I do after that is return that obj, but the function appears to run again and return the parent.
var model = [
{ name: 'Item 1' },
{
name: 'Item 2',
sub: [
{ name: 'Item 2.1' },
{ name: 'Item 2.2' },
{ name: 'Item 2.3' }
]
},
{ name: 'Item 3' },
{ name: 'Item 4' }
];
function getObj(collection, array) {
var data = collection[array[0]];
if(array.length > 1) {
array.shift();
arguments.callee(data.sub, array);
}
console.log('inside function', data);
return data;
}
var obj = getObj(model, [1, 2]); // expecting obj.name === 'Item 2.3'
console.log('result', obj); // obj.name === 'Item 2'
getObj(...)for better support?