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!

2
  • Object.keys(obj) returns an array of an object's property names. Commented Jun 26, 2018 at 17:26
  • 1
    "I get an [object Object] error" That's not an error. Commented Jun 26, 2018 at 17:26

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

1

Object.keys will do that.

var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.