使用key元素在json对象中查找值对

时间:2014-10-08 11:38:19

标签: javascript jquery json

参考此处发布的问题use jQuery's find() on JSON object 我有json对象,如果我将相应的关键元素传递给它,我想搜索元素的值

JSON:

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

当我将Mr.ABC作为我的功能的关键字传递时,我想要检索值Name

代码:

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;
}

现在输出为

[ ]

2 个答案:

答案 0 :(得分:1)

试试这个:

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;
}

通话功能:

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

See DEMO here.

答案 1 :(得分:1)

您需要为嵌套的json键(如

)递归调用代码
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 '';
}

正在使用 DEMO