我有一个包含 id 和类型值的数组 ({ id: '23', kind: 'apple' }, { id: '35', kind: broccoli }
),但是我有一个函数需要 id 的名称(假设 id 23 表示水果,id 35 表示蔬菜),例如“水果”或“蔬菜”。我写了一个不同的数组,其中包含 id 和 id 的名称 ({ id: '23', type: 'fruit' }, { id: '35', type: 'vegetable' }
).我如何过滤第一个数组,以便将 id 从说 23 或 35 更改为说水果或蔬菜?
最佳答案
您可以使用 Array#map
通过在哈希表中查找该 ID 来更改第一个数组中 ID 的值。
哈希表:
idHash = {'23': 'fruit', '35': 'vegetable'}
以便 idHash['23']
返回 "fruit"
数组#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)
输出 [{"id":"fruit","kind":"apple"},{"id":"vegetable","kind":"broccoli"}]
关于javascript - 如何根据不同的数组将数组的值更改为另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23573462/