Get values in an array of JSON objects
12,635
Solution 1
You mean something like this?
var a = [
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
];
function iter() {
for(var i = 0; i < a.length; ++i) {
var json = a[i];
for(var prop in json) {
alert(json[prop]);
// or myArray.push(json[prop]) or whatever you want
}
}
}
Solution 2
var json = [
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
for(var i in json){
var json2 = json[i];
for(var j in json2){
console.log(i+'-'+j+" : "+json2[j]);
}
}
Solution 3
Another solution:
var jsonArray = [
{ name: "Alice", text: "a" },
{ name: "Bob", text: "b" },
{ name: "Carol", text: "c" },
{ name: "Dave", text: "d" }
];
jsonArray.forEach(function(json){
for(var key in json){
var log = "Key: {0} - Value: {1}";
log = log.replace("{0}", key); // key
log = log.replace("{1}", json[key]); // value
console.log(log);
}
});
If you want to target newer browsers, you can use Objects.keys
:
var jsonArray = [
{ name: "Alice", text: "a" },
{ name: "Bob", text: "b" },
{ name: "Carol", text: "c" },
{ name: "Dave", text: "d" }
];
jsonArray.forEach(function(json){
Object.keys(json).forEach(function(key){
var log = "Key: {0} - Value: {1}";
log = log.replace("{0}", key); // key
log = log.replace("{1}", json[key]); // value
console.log(log);
});
});
Author by
tarnfeld
Updated on June 05, 2022Comments
-
tarnfeld almost 2 years
I have an array of JSON objects like so:
[ { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" } ]
I want to loop through them and echo them out in a list. How can I do it?