如何将该json对象设置为数组?

时间:2019-01-11 20:38:18

标签: javascript arrays object

我有这个json,我想将其转换为数组。

{  
    "match1": {
      "team1": "2",
      "team2": "0"
    },
    "match2": {
      "team1": "3",
      "team2": "1"
    }  
}

到目前为止,在搜索和查找类似问题之后,我已经提出了这个问题

var data = {
  "match1": {
    "team1": "2",
    "team2": "0"
  },
  "match2": {
    "team1": "3",
    "team2": "1"
  }
}

const array = Object.values(data.match1).map((key) => [key, data[key]]);

console.log(array);

// outputs 
//[2, , 0, ]

看起来不错,但是需要我为每个“ match”属性编写内容,并且我需要一种将它们一起输出的方法,因为match属性可以很多,例如match3,match4等。还不确定为什么要使用双逗号?

所以我想要的预期输出是

[[2,0], [3,1]];

怎么做?

2 个答案:

答案 0 :(得分:2)

var data = {  
    "match1": {
      "team1": "2",
      "team2": "0"
    },
    "match2": {
      "team1": "3",
      "team2": "1"
    }  
}

var result = Object.keys(data).map(key => Object.values(data[key]))

console.log(result)

如果要获取数值作为数字

var result = Object.keys(data).map(key => Object.values(data[key]).map(string  => parseInt(string)))

答案 1 :(得分:1)

var data = {"match1": {"team1": "2","team2": "0"},"match2": {"team1": "3","team2": "1"}}

var result = Object.values(data).map( val => Object.values(val) )

console.log(result);