Use a JSON array with objects with javascript

后端 未结 6 1590
执笔经年
执笔经年 2021-01-30 03:29

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:

6条回答
  •  悲&欢浪女
    2021-01-30 03:55

    This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:

    var arrayOfObjects = [{
      "id": 28,
      "Title": "Sweden"
    }, {
      "id": 56,
      "Title": "USA"
    }, {
      "id": 89,
      "Title": "England"
    }];
    
    for (var i = 0; i < arrayOfObjects.length; i++) {
      var object = arrayOfObjects[i];
      for (var property in object) {
        alert('item ' + i + ': ' + property + '=' + object[property]);
      }
      // If property names are known beforehand, you can also just do e.g.
      // alert(object.id + ',' + object.Title);
    }
    

    If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.

    var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
    var arrayOfObjects = eval(string);
    // ...
    

    To learn more about JSON, check MDN web docs: Working with JSON .

提交回复
热议问题