简体   繁体   中英

Get object key pair value based on a value

I have the following object:

const object1 = {
  language: 'somestring', abbr: 'abbr1',
  language: 'somestring2', abbr: 'abbr2',
  language: 'somestring3', abbr: 'abbr3',
  language: 'somestring4', abbr: 'abbr4',

};

My code will always have the abbr stored in a variable and this can change based on a user selection. What I'm trying to achieve is get the corresponding language if I know the abbr ie if I know abbr is equal to abbr3 I want to get somestring3.

you can't do that, having the same key inside the object, overrides the previous one

const object1 = {
    language: 'some_string1', abbr: 'abbr1',
    language: 'some_string2', abbr: 'abbr2',
    language: 'some_string3', abbr: 'abbr3',
    language: 'some_string4', abbr: 'abbr4',
  };

for(key in object1) {
    console.log(key, object1[key]);
}

I suggest you use nested objects

const object1 = {
  observation1: { language: "some_string1", abbr: "abbr1" },
  observation2: { language: "some_string2", abbr: "abbr2" },
  observation3: { language: "some_string3", abbr: "abbr3" },
  observation4: { language: "some_string4", abbr: "abbr4" },
};

for (named_observation in object1) {
  observation = object1[named_observation];
  for (key in observation) {
    console.log(named_observation, key, observation[key]);
  }
}

If you have an array of objects which have both language and abbr you could use Array. find :

 const arr = [ {language: 'somestring1', abbr: 'abbr1'}, {language: 'somestring2', abbr: 'abbr2'}, {language: 'somestring3', abbr: 'abbr3'}, {language: 'somestring4', abbr: 'abbr4'} ]; const knownAbbr = 'abbr3'; const correspondingLang = arr.find(obj => obj.abbr === knownAbbr)?.language; console.log(correspondingLang);

At first, I assume you have an array of objects, because JS object can not hold multiple properties of the same key. I suggest using an array of objects. In that case, solution would be something like this:

 const object1 = [ { language: 'somestring1', abbr: 'abbr1' }, { language: 'somestring2', abbr: 'abbr2' }, { language: 'somestring3', abbr: 'abbr3' }, { language: 'somestring4', abbr: 'abbr4' }, ] function getLangByAbbr (langList, abbr) { const lang = langList.find(lang => lang.abbr === abbr) return lang?.language } console.log(getLangByAbbr(object1, 'abbr2')) // 'somestring2' console.log(getLangByAbbr(object1, 'abbr4')) // 'somestring4' console.log(getLangByAbbr(object1, 'abbr9')) // undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM