最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterate over object and break - Stack Overflow

programmeradmin4浏览0评论

I have the following code:

const locales = {
  RU: 'something here',
  EN: 'something else here',
};

let locale;
for (const [key, value] of Object.entries(locales)) {
  if (key.indexOf('RU') !== -1) {
    locale = value;
    break;
  }
}

I am however using eslint. It's plaining about no-restricted-syntax, so I'm wondering how i can achieve the same result without a for loop (iteration with breaking).

ES7 is wele to be used.

I have the following code:

const locales = {
  RU: 'something here',
  EN: 'something else here',
};

let locale;
for (const [key, value] of Object.entries(locales)) {
  if (key.indexOf('RU') !== -1) {
    locale = value;
    break;
  }
}

I am however using eslint. It's plaining about no-restricted-syntax, so I'm wondering how i can achieve the same result without a for loop (iteration with breaking).

ES7 is wele to be used.

Share Improve this question edited Apr 13, 2017 at 14:43 basickarl asked Apr 13, 2017 at 14:38 basickarlbasickarl 40.6k69 gold badges238 silver badges357 bronze badges 4
  • please add some examples of valid keys with RU or are you looking for exactly RU as key? – Nina Scholz Commented Apr 13, 2017 at 14:40
  • You can do something like this: locale = locales[Object.keys(locales).find(k => k.indexOf("RU") != -1)]; – Titus Commented Apr 13, 2017 at 14:43
  • @NinaScholz Done! – basickarl Commented Apr 13, 2017 at 14:44
  • @Titus Spot on, post an answer and I'll accept. – basickarl Commented Apr 13, 2017 at 14:46
Add a ment  | 

4 Answers 4

Reset to default 4

You can do something like this:

const locales = {
  RUSSIAN: 'something here',
  ENGLISH: 'something else here',
};
let locale = locales[Object.keys(locales).find(k => k.indexOf("RU") != -1)];
console.log(locale);

You could access directly with the given key.

locale = locales.RU;

Or

var key = 'RU',
    locale = locales[key];

Use a function and call return

Use JavaScript's find Function. Something like this:

Object.entries(locales).find((value, key) -> key.indexOf("RU") !== -1);
发布评论

评论列表(0)

  1. 暂无评论