-2

I have a very specific JSON file, which format is quite annoying to deal with but no choice. This is really blocking me for such an easy task :

    const data = 
        {    
        "country":
            {
                "France" : 
                {
                    "owners" : ["peter", "john"],
                    "members" : [ "james", "paul"]
                },
                "Germany" :
                {
                    "owners" : ["Tom", "Omar"],
                    "members" : ["Zak", "Eddie", "Ronald"]
                },
                "Spain" : 
                {
                    "owners" : ["Juan"],
                    "members" : ["Clement", "Max"]
                }
            }
       }

All I want is a function that gets me the country of a specific user (Doesn't matter if he's among members or owners). For example :

GetUserCountry(data, 'Ronald'); // Should return 'Germany'

I know it's really simple but the format of the file won't let me do my things.

Nikhil
  • 6,493
  • 10
  • 31
  • 68
Zako
  • 151
  • 2
  • 11

1 Answers1

1

One approach would be to use Object.entries() and Array.find().

const data = {
  "country": {
    "France": {
      "owners": ["peter", "john"],
      "members": ["james", "paul"]
    },
    "Germany": {
      "owners": ["Tom", "Omar"],
      "members": ["Zak", "Eddie", "Ronald"]
    },
    "Spain": {
      "owners": ["Juan"],
      "members": ["Clement", "Max"]
    }
  }
};

function getUserCountry(data, name) {
  return Object.entries(data.country).find(([key, value]) =>
    (value.owners.includes(name) || value.members.includes(name)))[0];
}

console.log(getUserCountry(data, 'Ronald'));
console.log(getUserCountry(data, 'john'));
console.log(getUserCountry(data, 'Max'));
Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • The logic seems good but I still get the error : `Property 'owners' does not exist on type '{}'.ts(2339)` and same error for members – Zako Oct 07 '19 at 15:11
  • 2
    @Zako So add a type interface for that data, you only provided the JSON in the question. When you do, you should add it to the original question with an edit, please. – msanford Oct 07 '19 at 15:20
  • @Zako - Take a look at this [answer](https://stackoverflow.com/a/49467180/2924577) to fix that error. You can also use `value["owners"].includes(name)` and `value["members"].includes(name)` but you'll lose the benefits of static type checking. – Nikhil Oct 07 '19 at 15:20
  • It did the trick. I understand I lose a safety in my code but I don't care, the field will always be there so there shouldn't be any problem. I will now try to handle the case where the "name" parameter is not in the data and I'll be good to go. – Zako Oct 07 '19 at 15:32