Tech Learn
Tech Learn

Reputation: 61

How to compare obj of array1 with obj of array in javascript

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

Upvotes: 1

Views: 63

Answers (2)

Meyyappan Subramaniyan
Meyyappan Subramaniyan

Reputation: 363

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[] ...]

Upvotes: 0

Praveenkumar
Praveenkumar

Reputation: 2182

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))

Upvotes: 2

Related Questions