I’d like to construct html-elements from JSON-objects with multiple properties. My JSON-file looks like this:
[
{
"shape1": {
"fill": "red",
"stroke": "black",
"attr": {
"stroke-width": 5,
"color": "#000"
}
}
},
{
"shape2": {
"fill": "blue",
"stroke": "black",
"attr": {
"stroke-width": 3,
"color": "#d19930"
}
}
},
{
"shape3": {
"fill": "green",
"stroke": "black",
"attr": {
"stroke-width": 7,
"color": "#ffeb00"
}
}
}
]
I’d like to be able to turn each of these into an element, such as this:
<div data-fill:"green" data-stroke="black" data-stroke-width="5" data-color="#000"></div>
I’m stuck trying to get access to the properties of the objects. I’m fetching the objects like so:
$.getJSON( "/assets/svg-data/svg-forms1.json", function( data ) {
$.each(data, function(key, value) {
// What to do now?
})
});
When console log the objects, I can see that they have been fetched, but how do I now access the contents of the objects and use them?
2
Answers
Since the objects have different keys, and you’re not interested in the key, you can use
Object.values(value)[0]
to get the contained object that has the properties you want.Due to the complex nature of your data, you may need to iterate more than once. Here is a basic example.
As you can see, we iterate the Array, this gives us a number of Objects. Each of these Objects contains more Objects. Example:
This would have a value of “red”.
If you can adjust the Data being sent back, I would advise a different structure. Like so:
This will make iterating the data a lot easier.
Now you just have to iterate the Array alone.