1

I'm trying to get values from a nested JSON document. I wrote the following function:

var jsondata = {
'name': {
    'fname': 'Jack',
    'lname': [{'familyName': 'Sparrow'}, {'surname': 'Captain'}]
    }
};

var extracted = get_value(jsondata, 'familyName');
console.log(extracted); // null is getting printed

function get_value(dataObject, keyName) {
    value = null;

    for (var i in dataObject) {
        if (i == keyName) {
            value = dataObject[keyName];
            console.log(value); // getting correct value of 'familyName' here
            return value;
        } else if (typeof dataObject[i] == 'object') {
        get_value(dataObject[i], keyName);
        }
    }
    return value;
}

The problem is, I'm getting the correct value when printing console.log(value);, but null is getting printed by console.log(extracted);. Its like a return inside the for-in loop is not actually exiting the loop when the value is found.

What am I doing wrong? Thanks in advance.

2
  • I think it should be name.lname.familyname try it out once. @Sparky Commented Aug 19, 2013 at 10:27
  • Thanks @Kira, that kind of access will work, but I was trying more of a dynamic approach. Commented Aug 19, 2013 at 10:35

3 Answers 3

1

In your function you need to assign the value returned by get_value:

get_value(dataObject[i], keyName);

Should be:

value = get_value(dataObject[i], keyName);

Alternatively, just return the value:

return get_value(dataObject[i], keyName);
Sign up to request clarification or add additional context in comments.

1 Comment

Aah, that worked with the initial problem. But failed to work when I tried get_value(jsondata, 'surname'); instead of get_value(jsondata, 'familyName');
1

Finally I rewrote the code and now it will return the value of any given key in the json data:-

function get_value_nested(dataObject, keyName) {
    var value = null;
    this.get_value = function (dataObject, keyName) {
        for (i in dataObject) {
            if (i == keyName) {
                value = dataObject[keyName];
            } else if (typeof dataObject[i] == 'object') {
                 this.get_value(dataObject[i], keyName);
            }
        }
        return value;
    }

    this.get_value(dataObject, keyName);

    return value;
}

Comments

0

Remove value = null; from the function.

1 Comment

Then it will give undefined :)

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.