1

I have cascading filter dropdown, country dropdown and state dropdown. Once the selections are made, I need to redirect the user to the respective page. E.g.

    {
      USA + Texas : Texas URL,
      Germany + Berlin: Berlin URL
    } 

I can do this, but this makes no sense. I need the selected values pair to be the key.

{
 Texas URL: ["USA", "Texas"],
 Berlin URL: ["German", "Berlin"]
}

I need to create a data structure kind of like an Object map or hash table to capture this data.

Can someone give me suggestions on how best to create this data structure. Here is the my code so far:

https://jsbin.com/tarapijumi/3/edit?html,js,output

1
  • 1
    This isn't exactly what you asked for, but he very simplest way might be to make your key by concatenating the two strings like let country="USA", region="Texas"; let myKey = country + "-" + region; and separate them again later by finding the "-" character. ... It seems like using a more complex structure would just change the work of separating them later into different work of reintegrating them later (from different parts of the structure), but if you definitely prefer that, I can write an actual answer to address it. Commented Jan 23, 2019 at 20:58

2 Answers 2

2

You could take nested objects and take state and city as accessor

target = {
    USA: {
        California: 'http://example.com/usa/california',
        Texas: 'http://example.com/germany/texas'
    },
    Germany: {
        Frankfurt: 'http://example.com/germany/frankfurt',
        Berlin: 'http://example.com/germany/berlin'
    }
}

Access with an array, like

href = [country, state].reduce((r, k) => (r || {})[k], target)
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain that awesome line of code a bit more? Also with this type of data structure, i can technically get rid of the first object right? jsbin.com/zabiyafuqo/1/edit?html,js,output
it checks basically the object and takes either the truthy object or an empty object (to prevent an exception). Then it access with the key and return either the result or an object.
1

If you want to make it user friendly and clear in the code, I think the best way would be to have 2 dictionaries. One of all the countries with the cities of each, and one for the URL for each city:

countries = {
    "USA": ["California", "Texas"],
    "Germany": ["Berlin", "Leipzig"]
};

urls = {
    "Texas": "Texas URL",
    "California": "California URL",
    "Berlin": "Berlin URL",
    "Leipzig": "Leipzig URL"
};

And then, for the user-friendly part, you can do the following: when a country is selected, the next select would have options only for the cities of this country.

So if USA is selected, they would only see Texas and California in the next select.

I hope I helped you :-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.