简体   繁体   中英

Iterating through javascript array using ranged for loop

I have an MVC app where the controller takes a list of objects, serializes it using JavaScriptSerializer() creating a JSON object that is passed to the client side view.

For some reason, when I try to iterate through the object using a ranged for loop, each object is undefined, but when I iterate through the object with a regular for loop and index the object using the current iteration value in square brackets, I'm able to access each sub object (ie this works for(var i = 0; i < jsonObj.length; i++) vs this for(var sub in jsonObj) . Why doesn't the ranged for loop work in this instance?

JSON Object:

[
    "Obj1": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        },
        "Obj2": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        },
        "Obj3": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        }
]

EDIT

for(var sub in finalJson){
  console.log(sub["Value1"])
}

Your JSON is not valid, you either need to remove the object names so it's a valid list:

[{
   "Value1": "3454234",
   "Value2": "345643564",
   "Value3": "665445",
   "Value4": "True"
 }, {
   "Value1": "3454234",
   "Value2": "345643564",
   "Value3": "665445",
   "Value4": "True"
 } {
   "Value1": "3454234",
   "Value2": "345643564",
   "Value3": "665445",
   "Value4": "True"
 }]

in which case a ranged loop will work:

JsonObj.forEach(function(obj) {
   console.log(obj);
})

or convert it to an object containing the other objects as properties:

{
  "Obj1": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  },
  "Obj2": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  },
  "Obj3": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  }
}

in which case you can loop through via the keys:

for(var key in JsonObj) {
   console.log(key);
}

The reason your second loop wasn't working is because for..in is used to iterate through an objects keys, but your JSON is an array of objects, not an object

The JSON Object you've provide is not correct JSON object. It is an array of key-value pairs. Correct JSON object must be surrounded by { ... }, not by [ ... ]. You can check variable type jsonObj instanceof Array; If it gets true - then that is the reason.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM