[
"location": {
"country": {
"name": "Finland", "id": "FI"
},
"city":"Helsinki"
},
"location": {
"country": {
"name": "Russia", "id": "RU"
},
"city":"Helsinki"
}
]
let json = [
{"location": {
"country": {
"name": "Finland"
},
"city":"Helsinki"
}},
{"location": {
"country": {
"name": "Russia",
},
"city":"Moscow"
}},
{"location": {
"country": {
"name": "Russia",
},
"city":"Novgorod"
}},
{"location": {
"country": {
"name": "USA",
},
"city":"Boston"
}},
{"location": {
"country": {
"name": "Russia",
},
"city":"Ufa"
}},
{"location": {
"country": {
"name": "Australia",
},
"city":"Sidney"
}}
];
let wow = {
db: {},
parse(data) {
data.forEach(function({location: {country: {name: country}, city}} = node){
!this.db[country] ? (this.db[country] = {}, this.db[country][city] = true) : this.db[country][city] = true;
}, this);
return this;
},
render() {
function renderList(data) {
return `<ul>${renderCountries(data)}</ul>`
}
function renderCountries(data, html = '') {
Object.keys(data).forEach(country => html += `<li>${country}<ul>${renderCities(data[country])}</ul></li>`);
return html;
}
function renderCities(data, html = '') {
Object.keys(data).forEach(city => html += `<li>${city}</li>`);
return html;
}
return `<ul>${renderList(this.db)}</ul>`;
}
};
document.querySelector('body').innerHTML = wow.parse(json).render();
let arr =
[
{
"location":{
"country":{
"name":"Finland",
"id":"FI"
},
"city":"Helsinki"
}
},
{
"location":{
"country":{
"name":"England",
"id":"FI"
},
"city":"London"
}
},
{
"location":{
"country":{
"name":"Russian",
"id":"RU"
},
"city":"Moskow"
}
},
{
"location":{
"country":{
"name":"Russian",
"id":"RU"
},
"city":"Saint Petersburg"
}
},
{
"location":{
"country":{
"name":"Russian",
"id":"RU"
},
"city":"Sevastopol"
}
},
];
let all = [];
let bool = true;
for (var i = 0; i < arr.length; i++) {
for (var n = 0; n <= all.length; n++) {
if(all.length == 0) all.push({"country":arr[i].location.country.name,"city":[arr[i].location.city]});
bool = true;
for (var d = 0; d < all.length; d++) {
if(all[d].country==arr[i].location.country.name){
bool = false;
if(all[d].city.indexOf(arr[i].location.city)<0)all[d].city.push(arr[i].location.city);
};
}
if(bool)all.push({"country":arr[i].location.country.name,"city":[arr[i].location.city]});
}
}
console.log(all)
[
{
country: 'Finland',
city: ['Helsinki']
},
{
country: 'England',
city: ['London']
},
{
country: 'Russian',
city: ['Moskow', 'Saint Petersburg', 'Sevastopol']
}
]