【问题标题】:How do I change value of an array to another value based on a different array?如何根据不同的数组将数组的值更改为另一个值?
【发布时间】:2014-06-27 17:11:04
【问题描述】:

我有一个具有 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 更改为水果或蔬菜?

【问题讨论】:

  • 我可以使用 if else 语句或 switch case 语句,但必须有更简单的方法。

标签: javascript jquery arrays


【解决方案1】:

您可以使用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"}]

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多