2010-08-27 59 views
0

下我的問題選擇成JSON

是更多鈔票來選擇值到我的JSON對象,它的意思是要列出不同的學校,其中aaa研究

JSON對象看起來像這樣

[{」名稱「:」aaa「,」0「:」aaa「,」city「:」paris「,」1「:」paris「,」school「:」gtdzh「,」2「:」gtdzh「名稱「:」bbb「,」0「:」bbb「,」city「:」berlin「,」1「:」berlin「,」school「:」gdezh「,」2「:」gdezh「},{」名稱「:」ccc「,」0「:」ccc「,」city「:」new york「,」1「:」new york「,」school「:」asdzh「,」2「:」asdzh「 { 「名」: 「AAA」, 「0」: 「AAA」, 「城市」: 「悉尼」, 「1」: 「悉尼」, 「學校」: 「gtdcv」 「2」:「gtdcv」},{「名稱」:「bbb」,「0」:「bbb」,「城市」:「巴黎」,「1」:「巴黎」,「學校」:「gtdzh」, 「2」:「gtdzh」}]

感謝您的幫助

+0

http://stackoverflow.com/questions/1946165/json-find-in-javascript – 2010-08-27 16:33:57

回答

2

如果所有的名字都可以保證是唯一的,那麼你可以做這樣的事情:

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數據庫實現,但是我沒有與其中任何一個一起工作,所以我不能在這方面推薦任何東西。

+0

謝謝我正在嘗試現在要去 – tine 2010-08-27 17:11:12