1

I have an array that has an id and type value ({ id: '23', kind: 'apple' }, { id: '35', kind: broccoli }), but I have a function that requires a name for the id (pretend id 23 means fruits and id 35 means vegetables), such as 'fruits' or 'vegetables'. I write out a different array that has the id and the name for the id ({ id: '23', type: 'fruit' }, { id: '35', type: 'vegetable' }). How can I filter the first array so that I change the id from saying 23 or 35 to saying fruit or vegetable?

1
  • I could use an if else statement or a switch case statement, but there has to be an easier way. Commented May 9, 2014 at 20:38

1 Answer 1

5

You can use Array#map to change the value of the id on the first array by looking up that id in a hash table.

hash table:

idHash = {'23': 'fruit', '35': 'vegetable'}

so that idHash['23'] returns "fruit"

Array#map

array = [{id: '23', kind:'apple'},{id: '35', kind:'broccoli'}]
array = array.map(function(item){
  item.id = idHash[item.id] //Lookup the 'type' fromt he hash table
  return item
})

console.log(array)

outputs [{"id":"fruit","kind":"apple"},{"id":"vegetable","kind":"broccoli"}]

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.