JavaScript loop through JSON array?
JavascriptJsonJavascript Problem Overview
I am trying to loop through the following json array:
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
And have tried the following
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}
But for some reason I'm only getting the first part, id 1 values.
Any ideas?
Javascript Solutions
Solution 1 - Javascript
Your JSON should look like this:
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
You can loop over the Array like this:
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
Or like this (suggested from Eric) be careful with IE support
json.forEach(function(obj) { console.log(obj.id); });
Solution 2 - Javascript
There's a few problems in your code, first your json must look like :
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
Next, you can iterate like this :
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(json[key].id);
alert(json[key].msg);
}
}
And it gives perfect result.
See the fiddle here : http://jsfiddle.net/zrSmp/
Solution 3 - Javascript
try this
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
Solution 4 - Javascript
var arr = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
];
forEach method for easy implementation.
arr.forEach(function(item){
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
Solution 5 - Javascript
Since i already started looking into it:
var data = [{ "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "[email protected]"}, { "id": "2", "msg": "there", "tid": "2013-05-05 23:45", "fromWho": "[email protected]"}]
And this function
var iterateData =function(data){ for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key].id);
}
}};
You can call it like this
iterateData(data); // write 1 and 2 to the console
Update after Erics comment
As eric pointed out a for in
loop for an array can have unexpected results. The referenced question has a lengthy discussion about pros and cons.
Test with for(var i ...
But it seems that the follwing is quite save:
for(var i = 0; i < array.length; i += 1)
Although a test in chrome had the following result
var ar = [];
ar[0] = "a";
ar[1] = "b";
ar[4] = "c";
function forInArray(ar){
for(var i = 0; i < ar.length; i += 1)
console.log(ar[i]);
}
// calling the function
// returns a,b, undefined, undefined, c, undefined
forInArray(ar);
.forEach()
Test with At least in chrome 30 this works as expected
var logAr = function(element, index, array) {
console.log("a[" + index + "] = " + element);
}
ar.forEach(logAr); // returns a[0] = a, a[1] = b, a[4] = c
###Links
- see
for in
at the mdn - the new forEach method
- a comment that states that array comprehension makes
for in
less bad - Array comprehension introduced with javascript 1.7 in firefox 2 (yes 2)
Solution 6 - Javascript
It is working. I just added square brackets to JSON data. The data is:
var data = [ { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "[email protected]" }, { "id": "2", "msg": "there", "tid": "2013-05-05 23:45", "fromWho": "[email protected]" }]
And the loop is:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
Solution 7 - Javascript
Your data snippet need to be expanded a little, and it has to be this way to be proper JSON. Notice I just include the array name attribute item
.
{
"item": [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}]
}
Your JavaScript is simply
var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
var curitem = json.item[x];
}
Solution 8 - Javascript
It must be an array if you want to iterate over it. You're very likely missing [
and ]
.
var x = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
var $output = $('#output');
for(var i = 0; i < x.length; i++) {
console.log(x[i].id);
}
Check out this jsfiddle: http://jsfiddle.net/lpiepiora/kN7yZ/
Solution 9 - Javascript
A bit late but i hope i may help others :D
your json needs to look like something Niklas already said. And then here you go:
for(var key in currentObject){
if(currentObject.hasOwnProperty(key)) {
console.info(key + ': ' + currentObject[key]);
}
}
if you have an Multidimensional array, this is your code:
for (var i = 0; i < multiDimensionalArray.length; i++) {
var currentObject = multiDimensionalArray[i]
for(var key in currentObject){
if(currentObject.hasOwnProperty(key)) {
console.info(key + ': ' + currentObject[key]);
}
}
}
Solution 10 - Javascript
the very easy way!
var tire_price_data = JSON.parse('[{"qty":"250.0000","price":"0.390000"},{"qty":"500.0000","price":"0.340000"},{"qty":"1000.0000","price":"0.290000"}]');
tire_price_data.forEach(function(obj){
console.log(obj);
console.log(obj.qty);
console.log(obj.price);
})
Thank you.
Solution 11 - Javascript
Well, all I can see there is that you have two JSON objects, seperated by a comma. If both of them were inside an array ([...]
) it would make more sense.
And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop. As it is, I think it's going to try to retrieve the "id" property of the string "1", then "id" of "hi", and so on.
Solution 12 - Javascript
A short solution using map
and an arrow function
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
data.map((item, i) => console.log('Index:', i, 'Id:', item.id));
And to cover the cases when the property "id"
is not present use filter
:
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}, {
"msg": "abcde",
"tid": "2013-06-06 23:46",
"fromWho": "[email protected]"
}];
data.filter(item=>item.hasOwnProperty('id'))
.map((item, i) => console.log('Index:', i, 'Id:', item.id));
Solution 13 - Javascript
var json = {
"persons": [
{"name": "Lili", "age": 23, "is_student": true},
{"name": "James", "age": 24, "is_student": true},
{"name": "John", "age": 25, "is_student": false}
]
};
for (var key in json.persons) {
for (var keyName in json.persons[key]) {
alert(keyName + ': ' + (json.persons[key])[keyName]);
}
}
//Output: name:Lili, age:23, is_student:true, ...
Solution 14 - Javascript
you can use a for-loop then to get the values you can De-structure them
const arr = [
{
id:123,
desc:"do something",
isDone:false
},
{
id:124,
desc:"do something",
isDone:true
}
]
for(let _i in arr){
let {id, desc, isDone} = arr[_i]
// do something
console.log({id, desc, isDone});
}