I am trying to loop through the following json array:
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}
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?
Your JSON should look like this:
let json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];
You can loop over the Array like this:
for(let i = 0; i < json.length; i++) {
let 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); });
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": "hello1@email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];
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/
try this
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "hello1@email.se"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];
json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
var arr = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}
];
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);
});
Since i already started looking into it:
var data = [{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}]
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
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.
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()
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
for in
at the mdn for in
less bad 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": "hello1@email.se"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}
]
And the loop is:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
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": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}]
}
Your JavaScript is simply
var objCount = json.item.length;
for (var x = 0; x < objCount; x++) {
var curitem = json.item[x];
}
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": "hello1@email.se"
}, {
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "hello2@email.se"
}];
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/
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.
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]);
}
}
}
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.
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, ...
A short solution using map
and an arrow function
var data = [{ "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "hello1@email.se" }, { "id": "2", "msg": "there", "tid": "2013-05-05 23:45", "fromWho": "hello2@email.se" }]; 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": "hello1@email.se" }, { "id": "2", "msg": "there", "tid": "2013-05-05 23:45", "fromWho": "hello2@email.se" }, { "msg": "abcde", "tid": "2013-06-06 23:46", "fromWho": "hello3@email.se" }]; data.filter(item=>item.hasOwnProperty('id')) .map((item, i) => console.log('Index:', i, 'Id:', item.id));
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});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.