Home > Blockchain >  Compare arrays in vuejs
Compare arrays in vuejs

Time:10-15

{
   "product_hot": {
        "default": {
            "name": "Rose",
            "values": [
                "product_rose",
                "product_default"
            ]
        },
        "exclusive": {
            "name": "Cherry Blossom",
            "values": [
                "product_cherryBlossom",
                "product_exclusive",
            ]
        }
    },
}

I have retrieved the results from the database. and it is an array :

console.log(this.productType) // result: ['product_cherryBlossom', 'product_cherryBlossom'];

How do I compare this result with the object above, to get the key as :exclusive. My question may have a lot of mistakes.Please give me more feedback..Thanks

CodePudding user response:

Assuming that below is the comparable Object

let compObj = {
   "product_hot": {
        "default": {
            "name": "Rose",
            "values": [
                "product_rose",
                "product_default"
            ]
        },
        "exclusive": {
            "name": "Cherry Blossom",
            "values": [
                "product_cherryBlossom",
                "product_exclusive",
            ]
        }
    },
}

then you can try something like

// Function that returns keys as an array

getCategoryKey(resp, compObj) { // pass the response and compObj as arguments to this function
  let category = [];
  resp.forEach(item => {
    Object.keys(compObj.product_hot).forEach(categ => {
     if(compObj.product_hot[categ].values.includes(item)) {
       category.push(categ);
     }
    }
   }
  );
  console.log('Categories corresponding to your response', category);
 return category;
}

CodePudding user response:

Try like following snippet:

const product = {
   "product_hot": {
        "default": {
            "name": "Rose",
            "values": [
                "product_rose",
                "product_default"
            ]
        },
        "exclusive": {
            "name": "Cherry Blossom",
            "values": [
                "product_cherryBlossom",
                "product_exclusive",
            ]
        }
    },
}
const result = ['product_cherryBlossom', 'product_cherryBlossom']
const result2 = ['product_cherryBlossom', 'product_rose']

function findType(arr) {
  const res = []
  arr.forEach(r => {
    for(let key in product.product_hot) {
      if(product.product_hot[key].values.includes(r)) res.push(product.product_hot[key].name)
    }
  })
  return res
}
console.log(findType(result))
console.log(findType(result2))

  • Related