ObjectValues = function(v, k){
if (typeof v == "object") {
for (var kp in v) {
if (Object.hasOwnProperty.call(v, kp)) {
ObjectValues(v[kp], k != undefined ? k + "." + kp : kp);
}
}
} else {
console.log(k + ":" + v);
}
};
should work even for JSON values that are not objects. It will work for
ObjectValues(JSON.parse("0"));
which would not be handled by the original and it will not iterate over characters in a top-level string if you do ObjectValues("http://...").
ObjectValues = function(v, k){
if (typeof v == "object") {
for (var kp in v) {
if (Object.hasOwnProperty.call(v, kp)) {
ObjectValues(v[kp], k != undefined ? k + "." + kp : kp);
}
}
} else {
console.log(k + ":" + v);
}
};
should work even for JSON values that are not objects. It will work for
ObjectValues(JSON.parse("0"));
which would not be handled by the original and it will not iterate over characters in a top-level string if you do ObjectValues("http://...").
Use:
ObjectValues = function(obj) {
var isArray = obj instanceof Array;
for (var j in obj) {
if (obj.hasOwnProperty(j)) {
if (typeof(obj[j]) == "object") {
if(!isArray)
{
console.log(j + ":");
}
ObjectValues(obj[j]);
} else if(!isArray) {
console.log(j + ":" + obj[j]);
}
}
}
}
Note the removed loop. The way you were splitting it up, you were losing the k names.
You should also use hasOwnProperty to avoid serializing unwanted keys.
If the value is an object, you still want to serialize the key (e.g. you don't want to lose foo for {foo: {} }).
Finally, I had to do an array check, because arrays are objects, and we do want to output the keys nested within arrays, but we don't want to output the array indices themselves.
Demo at jsFiddle.
javascript - Iterate through nested json object array - Stack Overflow
Loop through a nested JSON object
JavaScript loop through JSON array? - Stack Overflow
javascript - Looping through nested json object - Stack Overflow
Videos
Since myJSONObject.abc contains a list of products it would make more sense to define the property abc as an array. Like this:
var myJSONObject =
{
"abc":
[
[
{"prod_ver" : "prod 1 ver 1"},
{"prod_ver" : "prod 1 ver 2"},
],
[
{"prod_ver" : "prod 2 ver 1"},
{"prod_ver" : "prod 2 ver 2"},
],
[
{"prod_ver" : "prod 3 ver 1"},
{"prod_ver" : "prod 3 ver 2"},
]
]
};
Then you can iterate over the products and their versions using normal loops:
for(var i = 0; i < myJSONObject.abc.length; i++)
{
var product = myJSONObject.abc[i];
for(var j = 0; j < product.length; j++)
{
var version = product[j];
}
}
You could take it slightly further and alter your JSON object's structure a bit to make it more easily understandable.
var catalog =
{
"products": [
{
"name": "prod 1",
"versions": [
"ver 1",
"ver 2"
]
},
{
"name": "prod 2",
"versions": [
"ver 1",
"ver 2"
]
}
]
};
for(var i = 0; i < catalog.products.length; i++)
{
var product = catalog.products[i];
var productName = product.name;
for(var j = 0; j < product.versions.length; j++)
{
var version = product.versions[j];
}
}
myJSONObject.abc is an object with keys like prod_1, prod_2, etc. You can loop through the keys of an object using for-in. So:
var productName;
var productVersionArray;
for (productName in myJSONObject.abc) {
productVersionArray = myJSONObject.abc[productName];
}
Note that the order of the keys is not defined by the specification and will vary from JavaScript engine to JavaScript engine. If you want to do them in a particular order, you have to get an array of them, sort it in the order you want, and then loop through that array. (In an ES5-enabled environment, you can get an array of the keys of an object from Object.keys(yourObject). But you'd need a shim for older browsers.)
Within that loop, you can loop through the array using a standard for loop:
for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
// Use `productVersionArray[versionIndex].prod_ver` here
}
Here's an example putting it all together:
(function() {
var myJSONObject =
{
"abc":
{
"prod_1":
[
{"prod_ver" : "prod 1 ver 1"},
{"prod_ver" : "prod 1 ver 2"}
],
"prod_2":
[
{"prod_ver" : "prod 2 ver 1"},
{"prod_ver" : "prod 2 ver 2"}
],
"prod_3":
[
{"prod_ver" : "prod 3 ver 1"},
{"prod_ver" : "prod 3 ver 2"}
]
}
};
var productName;
var productVersionArray;
var versionIndex;
for (productName in myJSONObject.abc) {
productVersionArray = myJSONObject.abc[productName];
display(productName + " has " + productVersionArray.length + " versions listed");
for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
display("* " + productVersionArray[versionIndex].prod_ver);
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
Live Copy | Source
Your JSON should look like this:
let 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(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": "[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/
You can do it using ecmascript 5's forEach method:
land.forEach(function(entry){
console.log(entry.name + " : " + entry.value)
} );
or use jquery to support legacy web browsers:
$.each(land,function(index,entry) {
console.log(entry.name + " : " + entry.value)
});
Don't loop through the subobject, just show its properties.
var land = [{
"name": "city",
"value": "Los Angeles"
}, {
"name": "state",
"value": "California"
}, {
"name": "zip",
"value": "45434"
}, {
"name": "country",
"value": "USA"
}];
$.each(land, function(index, object) {
console.log(object.name, ": ", object.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.
{
"dialog":
{
"trunks":[
{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
]
}
}
At that point, I was able to do a fairly simple for loop based on the total number of objects.
var totalMessages = Object.keys(messages.dialog.trunks).length;
for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
}
My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.
Hi all,
Im really struggling with this problem today. So basically, I have an array in the format
arr = [{title: " some title", id: "some id"}, {title: " some title2", id: "some id2"}] and all im trying to do is loop through each item in the array and get the value of the ids.
Here is what ive tried:
for( var i = 0; i< arr.length; i++){
console.log(arr[i].id)
}
It keeps showing up as undefined, please can anyone assist me? I would like the result to be "some id"