使用javascript搜索json数据中的密钥

时间:2017-01-05 19:58:41

标签: javascript

 filteredKeylist = [key for key, values in keyDict.items() if filterString in values]

当我不确定key2的位置时,如何获得key2的孩子?

2 个答案:

答案 0 :(得分:0)

var keys = Object.keys(data);

这将返回键名称的字符串数组。 ["key1", "key2"]

我认为你需要:

var childnames = Object.keys(data[key2]);

您可以通过以下方式将其转换为这些对象的数组:

var key2children = [];
for(var i=0; i< childnames.length; i++){
  key2children.push(data[key2][cildnames[i]);
}

编辑也许这有帮助?:

//To get the children of an object
function getChildObjects(tgtobj){
    var objchildren = [];
    objectkeys = Object.keys(tgtobj);
    for(var i=0; i< objectkeys.length; i++){
      key2children.push(tgtobj[objectkeys[i]);
    }
    return objectchildren;
}

//This could be used to get the children of a child object in a function like this:
function getChildOjectsOfChildByName(tgtobj, name){
    return getChildObjects(tgtobj[name]);
}

//usage example:
var key2childojects = getChildOjectsOfChildByName(data, "key2");

答案 1 :(得分:0)

您必须使用for循环和递归来获取嵌套密钥。

function searchObj(obj, searVal){
    for (ii in obj){
        if(ii === searVal){
            console.log(ii, ' -- my key');
        } else{
            console.log(ii, ' -- no key here');
            searchObj(obj[ii], searVal);
        }
    }
}
searchObj(data, 'child21');