Home > Enterprise >  Javascript .includes method on an array within an object
Javascript .includes method on an array within an object

Time:01-13

I want to filter through an array and retrieve items if their filters match. However it does not work.

const wanted=["apple"]
const items = [
  {
    "name": "Iphone"
    "filters": ["phone","apple"]
  },
  {
    "name": "samsung12"
    "filters": ["samsung12","samsung"]
  },
]

let desiredList = items.filter((val) => wanted.includes(val.filters));

Any ideas on how i could get this to work?

CodePudding user response:

You would need to use some to check if any of the filters contains a value in wanted:

const wanted = ["apple"]
const items = [{
  "name": "Iphone",
  "filters": ["phone", "apple"]
}, {
  "name": "samsung12",
  "filters": ["samsung12", "samsung"]
}];

let desiredList = items.filter((item) => item.filters.some((f) => wanted.includes(f)));

console.log(desiredList);

CodePudding user response:

const wanted="apple"
const items = [
"name": "Iphone"
"filters": ["phone","apple"]
]

let desiredList = 
items.filter((val)=> 
val.filters.includes(wanted) )

CodePudding user response:

simply you need to filter your items searching the required field, then map the result using .map for each result

here you can check it

let abc = document.querySelectorAll('div')

const wanted=["apple"]
const items = [{
  "name": "Iphone",
  "filters": ["phone","apple"]
},{
  "name": "Iphone",
  "filters": ["phone","sony"]
},{
  "name": "Iphone",
  "filters": ["phone","samsung"]
}]

items.filter((val) => val["filters"].includes(wanted[0])).map((item) => { item? abc[0].innerHTML  = item.name "<br />" item.filters : console.log("none") })
<div></div>

  • Related