ss814
ss814

Reputation: 109

How to get an array value in an object?

I've an object like this :

var routes = {
  'fr-FR': [
    '/accueil',
    '/offre',
    '/specifications'
  ],
  'en-US': [
    '/home',
    '/offer',
    '/specifications-en'
  ],
  'de-DE': [
    '/startseite',
    '/annbod',
    '/specificaties'
  ]
};

And my goal is to get the locale according to an url.

I tried something like : (url = /offer)

var getLocale = function(url) {
    console.log('getLocale for %s', url);
    for(var language in routes) {
         for(var route in language) {
             console.log('lg = ' + language);
             console.log('rt = ' + route);
             if (route === url) {
                return route;
             }
         }
    }
};

And the output I get is :

getLocale for /offer
lg = fr-FR
rt = 0
lg = fr-FR
rt = 1
lg = fr-FR
rt = 2
lg = fr-FR
rt = 3
lg = fr-FR
rt = 4
lg = en-US
rt = 0
lg = en-US
rt = 1
lg = en-US
rt = 2
lg = en-US
rt = 3
lg = en-US
rt = 4
lg = de-DE
rt = 0
lg = de-DE
rt = 1
lg = de-DE
rt = 2
lg = de-DE
rt = 3
lg = de-DE
rt = 4

So I guess I'm doing well for the first for-in loop but I don't know how to loop in the array instead of the chars of its name ...

Also, I read on many SO posts that for-in loops are not the best way to loop in certain cases but which ones?

Thanks in advance.

Upvotes: 2

Views: 81

Answers (2)

georg
georg

Reputation: 215009

Javascript iterators are usually more expressive than loops:

var routes = {
    'fr-FR': [
        '/accueil',
        '/offre',
        '/specifications'
    ],
    'en-US': [
        '/home',
        '/offer',
        '/specifications-en'
    ],
    'de-DE': [
        '/startseite',
        '/annbod',
        '/specificaties'
    ]
};

url = '/annbod'; // did you mean "angebot"?

locale = Object.keys(routes).filter(function(locale) {
    return routes[locale].indexOf(url) >= 0;
});

console.log(locale)[0]; // 'de-DE'

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

The first part of your loop is correct but notice: language is a string ("fr-FR", "en-US", etc.) not the array you're looking for.

Instead, you can access the routes by accessing routes[language] like this:

for (var language in routes) {
    var routeByLanguage = routes[language];
    for (var i = 0, len = routeByLanguage.length; i < len; i++) {
        console.log('lg = ' + language);
        console.log('rt = ' + routeByLanguage[i]);
        if (routeByLanguage[i] === url) {
            return routeByLanguage[i];
        }
    }
}

As for when to use for-in loops, you have* to use them on objects when you want to access their keys (like you do on your routes object). You shouldn't use them for arrays.

*You don't have to use them if you get the keys with Object.keys.

Upvotes: 7

Related Questions