Stackoverflow - retrieve values from JSON array using Jquery
http://stackoverflow.com/questions/23916834
by ubergoober
HTML
<div id="jQuery"></div>
<div id="nojQueryResults"></div>
<div id="IterateAllChildNodes"></div>
<div id="NoJqueryIterateAllChildNodes"></div>
CSS
div {padding: 10px}
JavaScript
var json = [
{
"id": "0004",
"name": "Test",
"image": {
"url": "images/0001.jpg",
"width": 200,
"height": 200
},
"Can": [
"250ml",
"300ml",
"330ml",
{
"image": "images/0001.jpg"
}
],
"Bottle": [
"350ml",
"600ml",
{
"image": "images/0001.jpg"
}
],
"Fountain": [
"small",
"large",
{
"image": "images/0001.jpg"
}
]
}
];
// jquery Example
$(json).each(function() {
if (this.name === "Test"){
console.log(this.Can);
console.log(this.Bottle);
console.log(this.Fountain);
$("#jQuery").append(JSON.stringify(this.Can)+"<br>");
$("#jQuery").append(JSON.stringify(this.Bottle)+"<br>");
$("#jQuery").append(JSON.stringify(this.Fountain)+"<br>");
};
});
// pure JS example
for (i = 0; i < json.length; i++ ) {
if (json[i].name === "Test"){
console.log(json[i].Can);
console.log(json[i].Bottle);
console.log(json[i].Fountain);
var out = document.getElementById("nojQueryResults");
out.innerHTML = out.innerHTML + JSON.stringify(json[i].Can)+"<br>";
out.innerHTML = out.innerHTML + JSON.stringify(json[i].Bottle)+"<br>";
out.innerHTML = out.innerHTML + JSON.stringify(json[i].Fountain)+"<br>";
};
};
// jquery Example iterate over all nodes when found
// json should be refactored to make an array in the found object
// that contains only what you want to extract here. Say maybe a type: key
// otherwise you'll get everything in this /flat/ node
$(json).each(function() {
if (this.name === "Test"){
$(this).each(function() {
console.log(this);
$("#IterateAllChildNodes").append(JSON.stringify(this)+"<br>");
})
...