Aspile Inc
Aspile Inc

Reputation: 119

Filter in Array into Array

I have a array of Object like this:

data() {
  return {
    searchVariant: null,
    variantList: ["red", "green", "blue"],
    products: [
      {
        id: 1,
        title: "adipisicing elit.",
        description: "ipsa deleniti.",
        variants: [
          { id: 1, color: "red", size: "xl", price: 150, inStock: 150 },
          { id: 2, color: "blue", size: "xl", price: 46, inStock: 4 },
          { id: 3, color: "gray", size: "sm", price: 50, inStock: 50 },
        ],
      },
      {
        id: 2,
        title: "amet consecteturt.",
        description: "id quas perspiciatis deserunt.",
        variants: [
          { id: 1, color: "red", size: "xl", price: 150, inStock: 150 },
          { id: 2, color: "blue", size: "xl", price: 46, inStock: 4 },
          { id: 3, color: "green", size: "sm", price: 50, inStock: 50 },
        ],
      },
    ],
  };
}

While I will select a variant like green in select-option, Row Number 2 will show in the table search list.

I am using Vuejs to do this:

queryResults() {
   if(this.searchVariant) {
       return this.products.filter((item)=> {
          return item.variants.filter((variant) => {
             return this.searchVariant.toLowerCase().split(' ').every(v => variant.color.toLowerCase().includes(v))
            })
          })
   }
   else{
    return this.products;
   }
}

Upvotes: 1

Views: 57

Answers (2)

Mahmud
Mahmud

Reputation: 41

You can try something like this

queryResults() {
 if(this.searchVariant) {
   return this.products.filter((item)=> {
     item.variants.some(variant => 
      variant.color.toLowerCase() === searchVariant.toLowerCase())   
   }
 }
 else{
  return this.products;
 }
}

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28414

You only need to check if every object in the array has some variant with the color matching your search:

const products = [
  {
     id: 1, 
     title: 'adipisicing elit.',
     description: 'ipsa deleniti.',
     variants: [
        {id: 1, color: 'red', size: 'xl', price: 150, inStock: 150},
        {id: 2, color: 'blue', size: 'xl', price: 46, inStock: 4},
        {id: 3, color: 'gray', size: 'sm', price: 50, inStock: 50}
     ]
  },
  {
    id: 2, 
    title: 'amet consecteturt.',
    description: 'id quas perspiciatis deserunt.',
    variants: [
        {id: 1, color: 'red', size: 'xl', price: 150, inStock: 150},
        {id: 2, color: 'blue', size: 'xl', price: 46, inStock: 4},
        {id: 3, color: 'green', size: 'sm', price: 50, inStock: 50}
    ]
 }
];
const searchVariant = 'green';

const result = products.filter(item =>
  item.variants.some(variant =>
    searchVariant.toLowerCase().includes(variant.color)
  )
);

console.log(result);

Upvotes: 2

Related Questions