如何迭代JSON对象并获取每个键的值

时间:2022-05-05 12:09:04

I have a JSONObject which had a JSONArray as a value for each key.

我有一个JSONObject,它有一个JSONArray作为每个键的值。

{
    "abc" : [null, "1,3", "2,4"],
    "dbs" : [null, "1,4", "4,5"],
    "sad" : [null, "6,2", "3,4", "5,5"]
}

I want to iterate over the object and take the JSONArray value for each key and put it into a string[]. Example for key: abc i would like to have a String[]: [null, "1,3", "2,4"]

我想迭代对象并为每个键获取JSONArray值并将其放入字符串[]。 key的示例:abc我想要一个String []:[null,“1,3”,“2,4”]

Could some one please help me with this?

有人可以帮我这个吗?

I have tried the following:

我尝试过以下方法:

for (var key in jsonObject) {
    if (jsonObject.hasOwnProperty(key)) {
        var array = jsonObject[key];
    }
}

But this gives me: ",1,3,2,4"

但这给了我:“,1,3,2,4”

1 个解决方案

#1


This should do the trick:

这应该做的伎俩:

function extract(data){
    return Object.keys(data).map(function(x){
        return data[x].filter(function(z){return z!==null;});
    });
}

Here is the fiddle to play with. For explanation of map, take a look at MDN

这是小提琴。有关地图的说明,请查看MDN

If you want to flatten the data, you could extend it to:

如果要展平数据,可以将其扩展为:

function flatten(data){
  return Object.keys(Object.keys(data).map(function(x){
    return data[x].filter(function(z){return z!==null;});
  }).reduce(function(o,n){
    n.forEach(function(x){
      o[x]=x;
    });
    return o;
  },{}));
}

#1


This should do the trick:

这应该做的伎俩:

function extract(data){
    return Object.keys(data).map(function(x){
        return data[x].filter(function(z){return z!==null;});
    });
}

Here is the fiddle to play with. For explanation of map, take a look at MDN

这是小提琴。有关地图的说明,请查看MDN

If you want to flatten the data, you could extend it to:

如果要展平数据,可以将其扩展为:

function flatten(data){
  return Object.keys(Object.keys(data).map(function(x){
    return data[x].filter(function(z){return z!==null;});
  }).reduce(function(o,n){
    n.forEach(function(x){
      o[x]=x;
    });
    return o;
  },{}));
}