【问题标题】:Replacing array with matching key in object用对象中的匹配键替换数组
【发布时间】:2020-10-30 18:25:12
【问题描述】:

我正在尝试创建一个函数,它将数组值替换为其匹配的对象值。我试过使用.filter。但是,它不允许重复值,如下例所示。

当前代码

        fetchInventory: async function () {
            await Object.entries(this.$store.state.inventory).forEach(([k, v]) => {
                for (let i = 0; i < parseInt(v); i++) this.inventory.push(parseInt(k))
            })

            const items = JSON.parse(localStorage.getItem('priceCache'));
            const filteredItems = await items.list.filter(i => this.inventory.includes(i[0]));

            this.inventory = await filteredItems;
        }

输入 var array = [1208, 1209, 1209]

电流输出

var output = [[1208, 'returned item'], [1209, 'returned item']]

预期输出

var output = [[1208, 'returned item'], [1209, 'returned item'], [1209, 'returned item']]

localStorage 对象

【问题讨论】:

  • 你在哪里使用array
  • 另一方面,想知道在丢失的两行中是否需要await
  • 试试[1208, 1209, 1209].map(e =&gt; [e, 'returned item'])
  • 它在 vue 中编码,在第一部分我将值推送到数据数组,@User863 我喜欢你的标题但“返回的项目”只是占位符,每个数字都有动态值。
  • 您从哪里获得这些动态值?请提供所有相关信息,以便我们为您提供帮助。

标签: javascript arrays dictionary object filter


【解决方案1】:

我猜你不希望filter 丢失array 中的任何值(例如这里的1209

所以你真正需要的是先map,然后是filter

var items = [1208, 1209] 
// inventory
var array = [1208, 1209, 1209] 
// filtered inventory
var output = array.map(i => items.includes(i) ? [i, 'returned item'] : undefined)
  .filter(i => i !== undefined)

console.log(output)

/** output:
(3) [Array(2), Array(2), Array(2)]
0: (2) [1208, "returned item"]
1: (2) [1209, "returned item"]
2: (2) [1209, "returned item"]
**/

【讨论】:

  • 为什么不简单地这样做呢? var array = [1208, 1209, 1209]; var res = array.map(i=&gt; [i, "returned value"]); console.log(res)
  • 因为他必须根据他发布的代码中的库存进行过滤。
  • 不是很清楚,因为他们刚刚定义了这样的输入var array = [1208, 1209, 1209];
【解决方案2】:

您似乎想要Array#mapArray#find

this.inventory = this.inventory.map(v=>[v, items.list.find(x=>x[0]===v)[1]);

【讨论】:

  • @Shimsho 没问题。
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多