选择JSON [英] select into JSON
问题描述
我的问题之后
有可能在我的JSon对象中选择值,这意味着要列出aaa学习过的不同学校
it is posible to select values into my JSon object that mean To list distinct schools where aaa studied
JSON对象如下
[{名称":"aaa","0":"aaa",城市":巴黎","1":巴黎",学校":"gtdzh","2":"gtdzh},{"名称:" bbb," 0:" bbb,"城市:"柏林," 1:"柏林,"学校:" gdezh," 2:" gdezh},{"名称:" ccc," 0:" ccc,"城市:"纽约," 1:"纽约,"学校:" asdzh," 2":"asdzh"},{名称":"aaa","0":"aaa",城市":"sidney","1":"sidney",学校":"gtdcv","2" :"gtdcv"},{名称":"bbb","0":"bbb",城市":巴黎","1":巴黎",学校":"gtdzh","2" :"gtdzh"}]
[{"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"}]
感谢您的帮助
推荐答案
如果可以保证所有名称都是唯一的,则可以执行以下操作:
If all of the names can be guaranteed to be unique then you can do something like this:
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
}
};
当然,如果您重复执行此类操作,则有更好的方法来解决此问题-从更改从服务器发送数据的方式到构建或使用诸如
Of course, there are better ways to go about this if you are doing this sort of thing repeatedly -- everything from changing the way the data is sent over from the server to building or using helper libraries like Underscore to do this sort of data-munging. There are also a few Javascript database implementations out there, but I haven't worked with any of them so I cannot recommend anything in that regard.
这篇关于选择JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!