1

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;
   }
}
0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
 }
}

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.