如果所有的名字都可以保證是唯一的,那麼你可以做這樣的事情:
var data_array = [
{"name":"aaa","0":"aaa","city":"paris","1":"paris","school":"gtdzh","2":"gtdzh"},
{"name":"bbb","0":"bbb","city":"berlin","1":"berlin","school":"gdezh","2":"gdezh"},
{"name":"ccc","0":"ccc","city":"new york","1":"new york","school":"asdzh","2":"asdzh"},
{"name":"aaa","0":"aaa","city":"sidney","1":"sidney","school":"gtdcv","2":"gtdcv"},
{"name":"bbb","0":"bbb","city":"paris","1":"paris","school":"gtdzh","2":"gtdzh"}
];
var l = data_array.length;
var i = 0
// We will use dict to store our output
var dict = {};
// Loop over the entire array
while (i < l) {
// Grab references to everything we need
var name = data_array[i].name;
var city = data_array[i].city;
// If we haven't seen this person before, add them to the dict
if (! Object.prototype.hasOwnProperty.call(dict, name)) {
dict[name] = {};
}
// Similarly, if we haven't heard of them studying in this city yet
// add that city to the "dictionary" of cities they've studied in
// and set the count of times they have studied in that city to 1.
if (! Object.prototype.hasOwnProperty.call(dict[name], city)) {
dict[name][city] = 1;
// Otherwise, increment the number of times they have studied in that city.
} else {
dict[name][city] += 1;
}
i++;
}
的最終結果將如下所示:
dict = {
"aaa": {
"paris": 1,
"sidney": 1
},
"bbb": {
"berlin": 1,
"paris": 1
},
"ccc": {
"new york": 1
}
};
當然,如果你反覆做這類事情的話,更好的方法是 - 從改變數據從服務器發送到構建或使用諸如Underscore等幫助程序庫來完成這種數據傳輸的方式。這裏也有一些Javascript數據庫實現,但是我沒有與其中任何一個一起工作,所以我不能在這方面推薦任何東西。
http://stackoverflow.com/questions/1946165/json-find-in-javascript – 2010-08-27 16:33:57