Reputation: 4641
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'
Upvotes: 0
Views: 66
Reputation: 120516
When you're recursing
arguments.callee(data.sub, array);
you're not returning the result, instead you're ignoring the result and returning data from the initial call.
Try adding a return
to that line so that the result of the recursive call is the result of the overall function.
Also be aware that arguments.callee
won't work in strict mode.
Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using
arguments.callee()
by either giving function expressions a name or use a function declaration where a function must call itself.
To work in strict mode, you could do
return getObj(data.sub, array);
Upvotes: 1
Reputation: 21769
You should return in the recursion as well:
function getObj(collection, array) {
var data = collection[array[0]];
if(array.length > 1) {
array.shift();
return arguments.callee(data.sub, array);
}
console.log('inside function', data);
return data;
}
Upvotes: 0