1

I'm stuck with the code. I actually want to filter elements in dataLayer using typescript/javascript.

I have dataLayer defined as shown below

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

}

track: { products }

products have {id,quantity}

dataLayers: { current: { cart: { items } } }

items have {id, brand, name, quantity }

Now I want to filter id and get the name of the product, For Example:

Example: *

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'}]
}*

Expected output

id:a123,name:'Reynolds'

id:a345,name:'Faber-Castell'

my code:

const id = products.map(product => { return product.id})
items.filter((item) => {
    return item.id === id
})
.map((item)=> {
   const { id, name } = item
   console.log("id" + id)
   console.log("name" + name)
})

Actual output

Giving error

**

const id: string[]
This condition will always return 'false' since the types 'string' and 'string[]' have no overlap.ts(2367)

**

Why am I not able to compare item.id with id

1
  • 3
    Cause id is an array. id.includes(item.id) Commented Nov 15, 2019 at 11:30

2 Answers 2

2

You are comparing the string array id with each item id which is a string. Do like below.

items.filter(item => id.includes(item.id))
Sign up to request clarification or add additional context in comments.

Comments

0

In the first line of your code, you are fetching the array of ids from products array. Hence id is nothing but an array.

const id: string[] = products.map(product => { return product.id })

Therefore, the below code will do the job.

items.filter((item) => id.includes(item.id) )

Also, If you are coding in typescript, develop the habit of using variable with its types. [number, string, boolean, string[] ...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.