Home > database >  How to sort Json file based on value of object?
How to sort Json file based on value of object?

Time:05-22

I have below json file named all, and contain below data

[{"name":{"common":"Dominican Republic","official":"Dominican Republic","nativeName":{"spa":{"official":"República Dominicana","common":"República Dominicana"}}},"region":"Americas","area":48671.0,"flags":{"png":"https://flagcdn.com/w320/do.png","svg":"https://flagcdn.com/do.svg"}},{"name":{"common":"Heard Island and McDonald Islands","official":"Heard Island and McDonald Islands","nativeName":{"eng":{"official":"Heard Island and McDonald Islands","common":"Heard Island and McDonald Islands"}}},"region":"Antarctic","area":412.0,"flags":{"png":"https://flagcdn.com/w320/hm.png","svg":"https://flagcdn.com/hm.svg"}},{"name":{"common":"Ghana","official":"Republic of Ghana","nativeName":{"eng":{"official":"Republic of Ghana","common":"Ghana"}}},"region":"Americas","area":238533.0,"flags":{"png":"https://flagcdn.com/w320/gh.png","svg":"https://flagcdn.com/gh.svg"}}]

I want to sort this file based on name.official value, I wrote below codes but it does not work. how can I achieve that?

const path = "../all.json;
getCuntries(path);

async function getCuntries(path) {
    const response = await fetch(path);
    const scrampled = await response.json();
    const parsed = await JSON.parse(JSON.stringify(scrampled));
    const data = parsed.sort(GetSortOrder("name"));
    console.log(data)
}

function GetSortOrder(prop) {
    return function(a, b) {
        if (a[prop][1] > b[prop][1]) {
            return 1;
        } else if (a[prop][1] < b[prop][1]) {
            return -1;
        }
        return 0;
    }
}

CodePudding user response:

Your comparator method is a bit messed up. First, comparing strings with > and < operators may lead to unexpected behaviour sometimes and this is not the recommended way to compare strings. And second (which is probably the root cause), you should access object values with their keys and not with indexes (like you’re doing with [1]). This should work - make it the body of function (a, b):

const aPassedProp = a[prop];
const bPassedProp = b[prop];
return aPassedProp.official.localeCompare(bPassedProp.official);

The localeCompare method can compare your strings in an appropriate way: you can learn more here.

CodePudding user response:

You can't access an object key by index. As it's is not specified if the object key should be dynamic, here a simple solution where it's not:

const data = [
  { "name": { "official": "Republic of Ghana"} },
  { "name": { "official": "Heard Island and McDonald Islands" } },
  { "name": { "official": "Dominican Republic" } },
]; // shortened for readability

const sortArray = (a, b) => {
  const aCompare = a.name.official;
  const bCompare = b.name.official;
  
  if (aCompare === bCompare) {
    return 0;
  }

  return aCompare < bCompare ? -1 : 1;
};

data.sort(sortArray);

console.log(data);

  • Related