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",
},
4
  • 1
    Does this answer your question? Sort array of objects by string property value Commented Apr 22, 2020 at 18:41
  • @Igor Beat me to it. Commented Apr 22, 2020 at 18:41
  • And first just use JSON.parse() to deserialize your JSON string, unless you already have an object. Commented Apr 22, 2020 at 18:44
  • Thanks @Igor . It works. Commented Apr 22, 2020 at 18:47

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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();
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.