anie
anie

Reputation: 519

Filter two arrays data based on nested ids

I have two arrays as follow:

const categories = [
  {"itemId": [1], "menuItemCateName": "Popular"}, 
  {"itemId": [1, 2], "menuItemCateName": "Featured"}
]

const items = [
  {
    "Id": 1,
    "price": 10,
    "itemName": "Spicy burger"
  },
  {
    "Id": 2,
    "price": 10,
    "itemName": "Pizza"
  }
]

I want to filter the data based on itemId inside array categories so the result will looks like

[
  { name: 'Popular', items: [ { "Id": 1, "price": 10, "itemName": "Spicy burger"} ] },
  { name: 'Featured', items: [ { "Id": 1, "price": 10, "itemName": "Spicy burger"},{ "Id": 2, "price": 10, "itemName": "Pizza"} ] }
]

What i tried is:

let data = []
categories.map(category => {

          items.filter(item => item.Id === category.itemId[0]).map(b => {
                  data.push({ 'name': category.menuItemCateName, 'items': [b] })
                })
           })

But I am getting this result:

 [
      { name: 'Popular', items: [ { "Id": 1, "price": 10, "itemName": "Spicy burger"} ] },
      { name: 'Featured', items: [ { "Id": 1, "price": 10, "itemName": "Spicy burger"} ] }
    ]

In the Featured category there should be two items data, but i am getting one item data because I am doing category.itemId[0] inside the filter function, which i have to loop inside the value of property itemId which i have no idea how to accomplish it. I will appreciate any help.

Upvotes: 0

Views: 279

Answers (1)

vaira
vaira

Reputation: 2270

Using map() to create new object and using filter() to add only matching itemIds

const categories = [
  {"itemId": [1], "menuItemCateName": "Popular"}, 
  {"itemId": [1, 2], "menuItemCateName": "Featured"}
]

const items = [
  {
    "Id": 1,
    "price": 10,
    "itemName": "Spicy burger"
  },
  {
    "Id": 2,
    "price": 10,
    "itemName": "Pizza"
  }
]


let result = categories.map(cat => {
  let newObject = { // creating new object with desired properties
    name: cat.menuItemCateName,
    items: items.filter(item => cat.itemId.some(s => s === item.Id)) // filtering matching its object
  }
  return newObject; 
})
console.log(result)
console.log('********* second object items have to values: ',result[1].items.length )
console.log(result[1].items)

Upvotes: 2

Related Questions