1

I have this json, which I want to convert to an array.

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

so far after searching and looking for simillar questions, I have come up with this

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, ]

It looks fine but it needs me to write for each 'match' property and I need a way to output them together as the match property can be many e.g match3, match4 e.t.c. also not sure why the double comma?

so the expected output I want is

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

how to do it?

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
user7716943
  • 485
  • 5
  • 15

2 Answers2

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)

If you want get values as number

var result = Object.keys(data).map(key => Object.values(data[key]).map(string  => parseInt(string)))
aseferov
  • 6,155
  • 3
  • 17
  • 24
  • 2
    The only technicality is that their desired output appear to be numbers rather than strings, but that's a trivial to fix – Matt Burland Jan 11 '19 at 20:43
  • It’s possible that neither the matches nor the teams will be in the expected order. – James Jan 11 '19 at 21:02
  • 1
    This could be reduce to: `Object.values(data).map(o => Object.values(o))` without the mapping to numbers. But is nice +1! – Shidersz Jan 11 '19 at 21:09
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);
ksav
  • 20,015
  • 6
  • 46
  • 66