0

I am currently trying to handle a GET request that returns a body in application/json structured like this:

{
    "items": {
        "item001": {"id":1234, "name": "name001"},
        "item002": {"id":1235, "name": "name002"},
        "item003": {"id":1236, "name": "name003"}
      }
}

I'm trying to get an array of strings that looks like

array = ["item001", "item002", "item003"];

I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.

In fact, each time I try to even print the name of a single key, for example

var obj = JSON.parse({'whole json here'});
print(obj.items[1]);

I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!

StudioTime
  • 22,603
  • 38
  • 120
  • 207
Nick S
  • 105
  • 6

3 Answers3

1

You can do Object.keys.It will return an array of the keys of an object

var x = {
  "items": {
    "item001": {
      "id": 1234,
      "name": "name001"
    },
    "item002": {
      "id": 1235,
      "name": "name002"
    },
    "item003": {
      "id": 1236,
      "name": "name003"
    }
  }
}

var y = Object.keys(x.items);

console.log(y)
brk
  • 48,835
  • 10
  • 56
  • 78
1

You can use Object.keys(). For Reference

var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
    
 var result = Object.keys(obj.items);
 
 console.log(result);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
1

Object.keys will do that.

var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );
amiraliamhh
  • 321
  • 2
  • 9