Toretto Toretto - 14 days ago 5
AngularJS Question

How to check if both the value exists or only one value exists in JavaScript object

I have an Object as below :

{"user": {
"name": "Harry Peter",
"phoneNumber": "12345",
"products": [
{
"type": "card",
"accountId": "5299367",
},
{
"type": "Loan",
"accountId": "5299365",
},
{
"type": "card",
"accountId": "8299388",
},
]}
}


What I need to find out if the user has both loan and card or just loan as user product.

Is there any built in function in javascript or angular to find it.

is someone has any suggestion how to do it. Please help.

Answer

You could use the filter array method.

var obj = {
    "user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [
        {
            "type": "card",
            "accountId": "5299367",
       },
        {
            "type": "Loan",
            "accountId": "5299365", 
        },
        {
            "type": "card",
            "accountId": "8299388", 
        },
     ]
  }
};
      
var loans = obj.user.products.filter(function(product){
      return product.type === "Loan";
});
      
console.log("Loans: " + loans.length);
      
// supposing that the user has either a Loan or a card. You could
// easily now find out if the user has only loans as below:
      
if(loans.length === obj.user.products.length){
    console.log("The user has only loans");
}else{
    var cards = obj.user.products.length - loans.length;
    console.log("The user has "+loans.length+" Loan(s) and "+ cards+ " Card(s).");
}
      

For further info about this method, please have a look here.

What I need to find out if the user has both loan and card or just loan as user product.

Based on the above snippet, by using the filter method and comparing the length of the loans with the length of the products, you can answer you question.

Comments