How to access JSON objects with spaces in Javascript

This is a tutorial on how to access JSON objects with spaces in Javascript.

For example, let's say you want to access something like this:

var test = {
    "user data": {
        "Full name": "John Doe",
        "id": "109"
    },
    "operating info": {
        "No. of interfaces": "4"
    }
}

And you need to know what's user data, for example. Well, it's done like so:

console.log(test["user data"]);

{Full name: "John Doe", id: "109"}

That wasn't that hard, was it?
If you want to iterate over test's children, that's also possible:

Object.keys(test).forEach(function(child) {
    console.log(test[child]);
});

> {Full name: "John Doe", id: "109"}
> {No. of interfaces: "4"}

Maybe you want to know what's Full name

var data = test["user data"];
console.log(data["Full name"]);

> John Doe

You can also log each child of user data:

Object.keys(data).forEach(function(child) {
    console.log(data[child]);
});

> John Doe
> 109

That's all there is to it. I hope you learned something...
Have a good day!

Comments

Popular posts from this blog

Made a Progressive Web App