假如有如下字符数组:
var City=['丽江',"宜宾","南京"];
var Province=["云南","四川","江苏"];
var Food = ["米线","燃面","雨花茶"];
想要将他们整合为如下JSON字符串,可以怎么做呢?
[{"city":"丽江","province":"云南","Food":"米线"},{"city":"宜宾","province":"四川","Food":"燃面"},{"city":"南京","province":"江苏","Food":"雨花茶"}]
先定义如下数据单元:
var CityJSON=[];//定义JSON对象存放各元素值
var CityItem={};//JSON对象中的元素值
CityItem是最终JSON对象中的一个抽象子元素,他应该包含三个属性值,分别为city,province,food,因此,需要对它进行赋值,最后将整体作为CItyJSON的子元素。
CityItem.city= City[i];
CityItem.province=Province[i];
CityItem.Food=Food[i];
CityJSON.push(CityItem);
如果只是这样的话,会出现一个问题,最终得到的JSON字符串的各个元素值是一样的,这个我还不清楚原因,有知道原因的可以解释一下,谢谢!要解决的话,需要在循环最后插入一句代码:
CityItem.city= City[i];
CityItem.province=Province[i];
CityItem.Food=Food[i];
CityJSON.push(CityItem);
CityItem={};
以下是没有CityItem={}这句代码的输出结果:
第一次循环的输出:
[{"city":"丽江","province":"云南","Food":"米线"}]
第二次循环的输出:
[{"city":"宜宾","province":"四川","Food":"燃面"},{"city":"宜宾","province":"四川","Food":"燃面"}]
第三次循环的输出:
[{"city":"南京","province":"江苏","Food":"雨花茶"},{"city":"南京","province":"江苏","Food":"雨花茶"},{"city":"南京","province":"江苏","Food":"雨花茶"}]
(上面的结果很奇怪,我也不太清楚原因,希望知道的可以出来解释一下)
所有正确代码如下:
var City=['丽江',"宜宾","南京"];
var Province=["云南","四川","江苏"];
var Food = ["米线","燃面","雨花茶"];
var CityJSON=[];//定义JSON对象存放各元素值
var CityItem={};//JSON对象中的元素值
for(i=0;i<City.length;i++){
CityItem.city= City[i];
CityItem.province=Province[i];
CityItem.Food=Food[i];
CityJSON.push(CityItem);
CityItem={};
console.log(JSON.stringify(CityJSON));
}
最终循环输出结果为:
[{"city":"丽江","province":"云南","Food":"米线"},{"city":"宜宾","province":"四川","Food":"燃面"},{"city":"南京","province":"江苏","Food":"雨花茶"}]