0

I'm trying to run through JSON, but some of the keys are random numbers and have otherwise unique names. I understand that you can select keys and their values if the key is predictable, but I'm unsure how to work with keys that aren't predictable.

Here is an example of some JSON:

{
"10193939": {
    "3948493": {
        "predictable_key1": "value1",
        "predictable_key2": "value2",
        "predictable_key3": [{
            "inner_predictable_key1": "value1"
        }]
    },
    "9898483": {
        "predictable_key1": "value1",
        "predictable_key2": "value2",
        "predictable_key3": [{
             "inner_predictable_key1": "value1"
        }]
    }
}

Now, I had some ideas, such as using a for each loops and remapping the inner unique keys to a new variable to bypass the outmost key. Is there an easy way to do this?

1 Answers1

1

You can iterate through the keys using the for...in clause.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

You can discover if the field belongs to the object direct, as opposed to part of the prototype using hasOwnProperty.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

If you're using a library like Lodash or underscore you can use the _.each function to iterate through the object keys and properties, or the _.keys to return all the keys in the object.

http://lodash.com/docs#keys

Beyond this, if you have a specific use case, you'd have to elaborate on your particular problem in greater detail.

Thinking Sites
  • 3,494
  • 17
  • 30
  • Essentially, my end goal is to create a personal website and using different APIs, have subpages where the APIs data is output into tables. So, in essence, it's more than iterating through JSON, but also translating the data nicely to HTML. – user3530268 Apr 14 '14 at 01:54
  • Then you're asking a much bigger architecture question than how to work with keys. I suggest getting acquainted with tools like KnockoutJS, jQuery templating, or lodash/underscore templating for something like this. – Thinking Sites Apr 14 '14 at 15:32