Reputation: 1
following my question
it is posible to select values into my JSon object that mean To list distinct schools where aaa studied
JSON object look like this
[{"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"}]
thank for your help
Upvotes: 0
Views: 257
Reputation: 159865
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++;
}
The end result will look something like this:
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.
Upvotes: 2