1

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”?

2 Answers 2

5

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}

Sign up to request clarification or add additional context in comments.

Comments

0

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.