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,502
  • 1
  • 17
  • 40
sam
  • 688
  • 1
  • 12
  • 35

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
  • 10,288
  • 1
  • 21
  • 32
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);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55