0

With reference to question posted here use jQuery's find() on JSON object I have json object in which i'd like to search value of the element if i passed respective key element to it

Json:

{"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}}

I want to retrieve value Mr.ABC when i passed Name as a key to my function

Code:

console.log(getObjects(ContextObj, 'Name'));

function getObjects(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (i == key) {
            objects.push(obj);
        }
    }
    return objects;
}

It gives output now as

[ ]
Community
  • 1
  • 1
Shaggy
  • 5,422
  • 28
  • 98
  • 163

2 Answers2

1

Try this:

var data = {"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}};
function find_value(key, inner_key) {
    var value = "";
    $.each(data.RESPONSE, function (i, k) {
        console.log(i, key, i == key)
        if (i == key) {
            value = k;
            return false;
        }
    });
    if (inner_key) {
        if (value[inner_key]) {
            value = value[inner_key];
        }
    }
    return value;
}

Calling function:

find_value("LASTBALANCE");
find_value("CUSTOMERDETAILS", "NAME");

See DEMO here.

codingrose
  • 15,563
  • 11
  • 39
  • 58
1

You need to call your code recursive for nested json keys like,

var s={"RESPONSE":{"@xmlns":"","CODE":"0","SECODE":"0","TXNID":"17527","LASTBALANCE":"-12078.8","SURCHARGE":"2","CUSTOMERDETAILS":{"NAME":"Mr.ABC"}}};
console.log(getObjects(s, 'NAME'));
console.log(getObjects(s, 'LASTBALANCE'));

function getObjects(obj, key) {
    var objects = [];
    for (var i in obj) {
        if(typeof obj[i] == 'object'){
            return getObjects(obj[i], key); // if it is an object then find the key recursively.
        }
        if (!obj.hasOwnProperty(i)) continue;

        if (i == key) {
            return obj[key];
        }
    }
    return '';
}

Working DEMO

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106