Reputation: 438
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?
Upvotes: 1
Views: 65
Reputation: 3892
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.
idHash = {'23': 'fruit', '35': 'vegetable'}
so that idHash['23']
returns "fruit"
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"}]
Upvotes: 5