【发布时间】:2019-12-11 03:59:26
【问题描述】:
我被代码卡住了。我实际上想使用 typescript/javascript 查找 dataLayer 中元素的索引。
track: { products },
dataLayers: { current: { cart: { items } } }
products?: IProduct[]
export interface IProduct {
id: string
quantity?: string
name?: string
}
items?: ICartItem[]
export interface ICartItem {
id: string
brand: string
name: string
quantity: number
}
跟踪:{产品}
产品有 {id,quantity}
dataLayers: { current: { cart: { items } } }
商品有{id, brand, name, quantity}
现在我想查找产品的位置/索引,例如:
示例:*
products:{
[{id: 'a123',quantity: '1'},{id:'a345', quantity:'2'}]
}
items:{
[{id: 'a123',brand:'pen',name: 'Reynolds', quantity: '1'}, {id: 'a143',brand:'pencil',name: 'Nataraj', quantity: '3'}, {id: 'a122',brand:'pen',name: 'Parker',quantity: '1'},{id:'a345',brand:'Eraser',name: 'Faber-Castell', quantity:'2'}]
}
{id:'a123',quantity:'1'} 的位置应该是 1 和 {id:'a345',quantity:'2'} 的位置> 应该是 4
我的代码如下所示:
我已经使用 map 从 products 中获取 id,如图所示
const id = products.map(product => { return product.id})
现在我想在项目中找到这些产品的索引/位置。所以我尝试如下
let position = filter((item: ICartItem) => {
if(id.includes(item.id)){
return {id}
}
}).findindex(id)
即,
const id = products.map(product => { return product.id})
let position = filter((item: ICartItem) => {
if(id.includes(item.id)){
return {id}
}
}).findindex(id)
但我收到错误
'string[]' 类型的参数不能分配给'(value: ICartItem, index: number, obj: ICartItem[]) => unknown' 类型的参数。 类型 'string[]' 不匹配签名 '(value: ICartItem, index: number, obj: ICartItem[]): unknown'.ts(2345)
有人帮我找到过滤产品的位置/索引?
【问题讨论】:
-
什么是
filter()(为什么和.map()一样)?ivm是什么?没有.findindex()只有.findIndex()需要一个函数而不是一个数组。
标签: javascript node.js typescript