0

I have a live API which has data in JSON format and I trying to display it on my website (for web development learning). I did request the data have a the data displayed on my website but the problem is how do I order my data by 'Country"? Any help please

"countries": [
{
  "country": "United States",
  "countryCode": "US",
},
{
  "country": "Spain",
  "countryCode": "ES",
},
Aqeel
  • 31
  • 1
  • 1
  • 6

2 Answers2

1

U can try

sortbyKey(obj,key){
  return obj.sort(function(a, b) {
    var keyA = a[key],
      keyB = b[key];
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
  });

}

example is below

var list={"countries": [
{
  "country": "United States",
  "countryCode": "US",
},
{
  "country": "Spain",
  "countryCode": "ES",
}
]
}

function sortbyKey(obj,key){
  return obj.sort(function(a, b) {
    var keyA = a[key],
      keyB = b[key];
    if (keyA < keyB) return -1;
    if (keyA > keyB) return 1;
    return 0;
  });
  
}
list.countries=sortbyKey(list.countries,"country")

console.log(list)
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
1

First, create a model class that represents your incoming object as shown below -

export class Countries {
    country: string;
    countryCode: string;
}

Then initialize it as an array of objects -

countriesModel : Countries [] = [];

Convert your JSON to a model by parsing it -

this.countryModel = JSON.parse(your_country-object);

After that call the sortCountries function and pass the property in the object on which you want to sort -

this.sortCountries(p => p.country, 'ASC');

Finally, your sort functions body should look something like this -

sortCountries<T>(countryName: (c: countriesModel) => T, order: 'ASC' | 'DESC'): void {
this.countriesModel.sort((a, b) => {
  if (countryName(a) < countryName(b)) {
    return -1;`enter code here`
  } else if (countryName(a) > countryName(b)) {
    return 1;
  } else {
    return 0;
  }
});

if (order === 'DESC') {
  this.countriesModel.reverse();
}

}