0

I have a JSON object that has the following structure

{"30-31":[{"msg":"hello","usr":"31"}],
"33-30":[{"msg":"shah hi","usr":"30"}]}

What operation can I perform to get an array like this ["30-31", "33-30"]. I tried my best using .map etc but with no success, can anybody help?

Roy Berris
  • 1,310
  • 1
  • 13
  • 34
sam
  • 678
  • 1
  • 10
  • 34

2 Answers2

5

you can use Object.keys()

let obj = {"30-31":[{"msg":"hello","usr":"31"}],
  "33-30":[{"msg":"shah hi","usr":"30"}]}
  
console.log(Object.keys(obj));
marvel308
  • 9,972
  • 1
  • 18
  • 31
5

There is a built-in Object.keys(obj) that you can use:

var json = {"30-31":[{"msg":"hello","usr":"31"}],
            "33-30":[{"msg":"shah hi","usr":"30"}]};
var keys = Object.keys(json);
console.log(keys);

Additionally, you can do it the hard (cross-browser) way with a for...in loop:

var json = {"30-31":[{"msg":"hello","usr":"31"}],
            "33-30":[{"msg":"shah hi","usr":"30"}]};
var keys = [];
for (k in json) keys.push(k);
console.log(keys);
MrGeek
  • 21,097
  • 4
  • 28
  • 52