有这样一组数据
{"a":"0","b":"OK","c":[{"Account":"81614031","Time":"2012-11-26"},{"Account":"81614032","Time":"2012-11-26"},{"Account":"81614033","Time":"2012-11-26"},{"Account":"81614034","Time":"2012-11-26"},{"Account":"816140315","Time":"2012-11-26"},{"Account":"816140311","Time":"2012-11-26"},{"Account":"816140312","Time":"2012-11-26"},{"Account":"816140311","Time":"2012-11-26"}]}
我想将Account对应的号码提出来显示列表中,相同的只显示一次。
如:816140311,816140312,816140313,816140314,816140315这样显示。
请问用js怎么写呢?
var json_data={....};//你上面的数据 var data={}; for(var i=0; i<json_data.c.length; i++){ data[json_data.c[i].Account]=""; } var result=""; for(var p in data){ result+=p+","; } alert(result);
能看到结果了
for(var i=0; i<json_data.c.length; i++){ data[json_data.c[i].Account]=""; }
请问这里为什么要这么写呢,有什么用处
@jq2727:
这里把data这个对象当作字典,把Account作为键存起来,这样每个键都不会重复(重复的自动覆盖了)。
最终data={"81614032":"","81614033":"",...},
然后用for(...in..)来遍历所有键(对象属性)。
Array.prototype.noRepeated=function(){ var newArray=[], flags={}; for (var i=0;i<this.length;i++){ var item= this[i]; if (!flags[item]) { newArray.push(item); flags[item] = true; } } return newArray; } var a={"a":"0","b":"OK","c":[{"Account":"81614031","Time":"2012-11-26"},{"Account":"81614031","Time":"2012-11-26"}]} var cItems=a.c; var sourceArray= []; $(cItems).each(function(index){ sourceArray.push(cItems[index].Account) }); sourceArray=sourceArray.noRepeated(); alert(sourceArray.join(","));
1 var str = '{"a":"0","b":"OK","c":[{"Account":"816140311","Time":"2012-11-26"},{"Account":"81614032","Time":"2012-11-26"},{"Account":"81614033","Time":"2012-11-26"},{"Account":"81614034","Time":"2012-11-26"},{"Account":"816140315","Time":"2012-11-26"},{"Account":"816140311","Time":"2012-11-26"},{"Account":"816140312","Time":"2012-11-26"},{"Account":"816140311","Time":"2012-11-26"}]}'; 2 var arr = eval('(' + str + ')').c; 3 var obj = {}; 4 for (var i = 0, len = arr.length; i < len; i++) { 5 if (obj[arr[i].Account] == undefined) { 6 obj[arr[i].Account] = 1; 7 } 8 } 9 var array = new Array(); 10 for (var i in obj) { 11 array[array.length] = i; 12 } 13 var result = array.join(','); 14 alert(result);
相同所有的
Account取出来放一个数组中,去掉书中重复的数
能看到结果了
for (var i = 0, len = arr.length; i < len; i++) { if (obj[arr[i].Account] == undefined) { obj[arr[i].Account] = 1; } }
请问这里为什么要这么写呢,有什么用处?
@jq2727:
你可以去了解下JavaScript的Array。把值当作索引,存在则舍弃。