Pergunta

Currently the way that I am taking a JSON string where I "Don't know the contents" and pulling the keys and the values is as follows:

var arr     =   [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var arrLen  =   arr.length;
for(var i = 0; i < arrLen; i++){
    var myKeys      =   Object.keys(arr[i]);
    var keysLen     =   myKeys.length;
    for(var x = 0; x < keysLen; x++){
        keyName     =   myKeys[x];
        keyValueStr =   "arr[i]."+keyName;
        keyValue    =   eval(keyValueStr);
        console.log(keyName+':'+keyValue);
    }
}

There has to be a cleaner and more efficient way of doing this. Any suggestion would be appreciated.

Foi útil?

Solução

Using jQuery you can use http://api.jquery.com/jQuery.parseJSON/ & Object.keys - Than:

var obj = jQuery.parseJSON('{"manager_first_name":"jim","manager_last_name":"gaffigan"}');
var keys = Object.keys(obj);
jQuery.each(keys,function(k, v){
    console.log(v);
    console.log(obj[v]);
});

Outras dicas

Create an object and initialize it with your JSON:

var arr     =   [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var JSONObject = new MyJSONObject(arr);

in your constructor, set the object's properties.

You could use for-in loop which iterates over the enumerable properties of an object, in arbitrary order.

var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
for (var i = 0; i < arr.length; i++) {
    var currentObj = arr[i];
    for (var item in currentObj) {
        console.log(item + " : " + currentObj[item]);
    }
}

If your array always have only one item, you could omit the outermost for loop and just use arr[0]

var currentObj = arr[0];
for (var item in currentObj) {
    console.log(item + " : " + currentObj[item]);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top