6, JSON array

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/LOVEYSUXIN/article/details/102730660

6, JSON array

As an array of JSON objects:

Examples

[  "Porsche", "BMW", "Volvo" ]

JSON arrays in almost the same as in JavaScript array.

In the the JSON, it must belong to the type of array values strings, numbers, objects, arrays, Boolean, or null.

In JavaScript, array values ​​may be all types of the above, plus any other valid JavaScript expression, including functions, date and undefined.

JSON object array

Arrays can be the value of the object properties:

{
"name":"Bill Gates",
"age":62,
"cars":[ "Porsche", "BMW", "Volvo" ]
}

Iterate

By using the for-in loop or loop for access to an array of values:

// for-in
for (i in myObj.cars) {
     x  += myObj.cars[i];
}

// for 循环
for (i  = 0; i < myObj.cars.length; i++) {
    x  += myObj.cars[i];
}
Nested array JSON object

Values ​​in the array may be another array, or even another JSON object:

myObj =  {
   "name":"Bill Gates",
   "age":62,
   "cars": [
	  { "name":"Porsche",  "models":[ "911", "Taycan" ] },
	  { "name":"BMW", "models":[ "M5", "M3", "X5" ] },
	  { "name":"Volvo", "models":[ "XC60", "V60" ] }
   ]
}

To access the array inside an array, use the for-in loop for each array:

for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].name  + "</h1>";
    for (j in myObj.cars[i].models) {
         x += myObj.cars[i].models[j];
    }
}
Modify array values

Use the index number to modify the array:

myObj.cars[1] = "Mercedes Benz";
Delete Array Project

Use keywords to delete delete items in the array:

delete myObj.cars[1];

Guess you like

Origin blog.csdn.net/LOVEYSUXIN/article/details/102730660