user12097954
user12097954

Reputation:

JavaScript find key by a value in array

I have data structured like this:

var states = {
  'alabama': { abbv:'AL', ec: 9, winner: 0},
  'alaska': { abbv:'AK', ec: 3, winner: 0},
  'arizona': { abbv:'AZ', ec: 11, winner: 0}
}

How would I find “Alaska” by say searching for “AK”?

Upvotes: 1

Views: 57

Answers (2)

Felipe Oriani
Felipe Oriani

Reputation: 38608

There is a lot of ways to implement it, this example bellow is a dynamic one, which takes a source, 'prop' (property) and a value. For example:

function getByProp(source, prop, value) {
  let item = Object.keys(source).filter(key => source[key][prop] === value);
  if (item){
    return source[item[0]];
  }

  return null;
}

let alaska = getByProp(states, 'abbv', 'AK'); // -> alaska prop from states object!

Then you just pass the arguments which are 'states', 'abbv', and 'AK'.

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113365

Iterate the state names (keys) and use the find method to return the right state.

var states = {
  'alabama': { abbv:'AL', ec: 9, winner: 0},
  'alaska': { abbv:'AK', ec: 3, winner: 0},
  'arizona': { abbv:'AZ', ec: 11, winner: 0}
}
const searchFor = "AK"
const foundState = Object.keys(states).find(stateName => {
  return states[stateName].abbv === searchFor
})

console.log(foundState)
// => "alaska"

console.log(states[foundState])
// => { abbv:'AK', ec: 3, winner: 0}

Upvotes: 5

Related Questions