从JSON对象创建数组

时间:2017-03-17 12:07:53

标签: javascript arrays json object

以下是我的JSON对象

var validation_messages ={
"test1": [{
    "1": {

        "rssi": -25,

    }
}, {
    "2": {

        "rssi": -25,

    }
}],
"test2": [{
    "15": {

        "rssi": -10,
                }
}, {
    "19": {

        "rssi": -21,

    }
}]

}

以下就是我试过的

var rssival = []; for(validation_messages中的var键){

var obj = validation_messages[key];

for (var i=0; i<obj.length; i++) {
  for(x in obj[i]){

   rssival.push(obj[i][x].rssi);
  } 
}

} 的console.log(rssival)

我的输出为

[-25, -25, -10, -21]

但我需要一个输出

[[-25, -25], [-10, -21]]

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:5)

您可以尝试这样的事情:

&#13;
&#13;
var validation_messages={"00:11:74:41:3d:f0":[{1:{channel:1,type:2,rssi:-25,rate:24}},{2:{channel:1,type:2,rssi:-25,rate:24}}],"00:23:68:bd:6c:19":[{15:{channel:1,type:0,rssi:-10,rate:1}},{19:{channel:1,type:2,rssi:-21,rate:54}}]};

var result = Object.keys(validation_messages).map(function(k){
  var tmp = [];
  validation_messages[k].forEach(function(o){ 
    for(var k in o){
      tmp.push(o[k].rssi)
    }
  })
  return tmp
});
console.log(result)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这不是你需要的吗?

var validation_messages={"00:11:74:41:3d:f0":[{1:{channel:1,type:2,rssi:-25,rate:24}},{2:{channel:1,type:2,rssi:-25,rate:24}}],"00:23:68:bd:6c:19":[{15:{channel:1,type:0,rssi:-10,rate:1}},{19:{channel:1,type:2,rssi:-21,rate:54}}]};

var rssival = [];

for (var key in validation_messages) {
  var obj = validation_messages[key];
  var aux = [];
  for (var i = 0; i < obj.length; i++) {
    for (x in obj[i]) {
      aux.push(obj[i][x].rssi);
    }
  }
  rssival.push(aux);
}
console.log(rssival);

https://jsfiddle.net/etbzjs0x/

答案 2 :(得分:1)

另一种方法。

&#13;
&#13;
var obj = {"00:11:74:41:3d:f0":[{1:{channel:1,type:2,rssi:-25,rate:24}},{2:{channel:1,type:2,rssi:-25,rate:24}}],"00:23:68:bd:6c:19":[{15:{channel:1,type:0,rssi:-10,rate:1}},{19:{channel:1,type:2,rssi:-21,rate:54}}]},
    result = Object.keys(obj).map(function(v) {
      var arr = [];
      obj[v].forEach(c => arr.push(c[Object.keys(c)].rssi));
      return arr;
    });

    console.log(result);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用Array#map对所有媒体资源进行分组。

&#13;
&#13;
var validation_messages = validation_messages = { "00:11:74:41:3d:f0": [{ "1": { channel: 1, type: 2, rssi: -25, rate: 24 } }, { "2": { channel: 1, type: 2, rssi: -25, rate: 24 } }], "00:23:68:bd:6c:19": [{ "15": { channel: 1, type: 0, rssi: -10, rate: 1 } }, { "19": { channel: 1, type: 2, rssi: -21, rate: 54 } }] },
    grouped = Object.keys(validation_messages).map(function (k) {
        return validation_messages[k].reduce(function (r, o) {
            Object.keys(o).forEach(function (l) {
                r.push(o[l].rssi);
            });
            return r;
        }, []);
    });

console.log(grouped);
&#13;
&#13;
&#13;