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?
-
I could use an if else statement or a switch case statement, but there has to be an easier way.ChrisRockGM– ChrisRockGM2014-05-09 20:38:36 +00:00Commented May 9, 2014 at 20:38
Add a comment
|
1 Answer
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"}]