0

I want to find an element with some id in multilevel JSON object. I use recursion with angular.forEach method, but the method returns undefined even though return value; is reached.

Here is method:

    function findLaoutFieldByID(array, search) {
        if (!array || !search) {
            return null;
        }
        angular.forEach(array, function(value, key) {
            if (value.id == search) {
                return value;
            }
            return findLaoutFieldByID(value.items, search);
        });
    }sql

Maybe someone can tell me why?

Maybe someone can suggest how to find an object with id=rc2 in this array. I tried recursion, but had no luck.

        $scope.containerLayout = [ {
        id : 'root',
        size : '100%',
        direction : 'row',
        items : [ {
            id : 'rc1',
            size : '50%',
            direction : 'col',
            items : [ {
                id : 'rc11',
                size : '40%'
            }, {
                id : 'rc12',
                size : '40%'
            }, {
                id : 'rc13',
                size : '20%'
            } ]
        }, {
            id : 'rc2',
            size : '50%'
        } ]
    } ];

I found some solution, not sure if it is best, but is someone else needs:

        function findLaoutFieldByID(array, search) {
        if (!array || !search) {
            return null;
        }

        for (var i = 0; i < array.length; i++) {
            if (array[i].id == search) {
                return array[i];
            }
            var returns = 0;
            if (array[i].items) {
                while (returns != array[i].items.length) {
                    var val = findLaoutFieldByID(array[i].items, search);
                    if (val == null) {
                        returns++;
                    } else {
                        return val;
                    }
                }
            }
        }
        return null;
    }
1
  • 2
    You're returning from the iteration-function not from findLaoutFieldByID. Commented Sep 23, 2015 at 18:23

1 Answer 1

2

You're returning from the function that's iterating (angular.forEach), not from findLaoutFieldByID. You might want to use a regular for loop.

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

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.