Neha Kumari
Neha Kumari

Reputation: 1

How to filter out an array of objects on a basis of a given param?

I have this array:

[
  {
    "prod": {
      "a": "b",
      "mdh": "nui";
    },
    "prod_merchant": {
      "prod_delivery": "Express",
      "site": 45
    }
  },
  {
    "prod": {
      "a": "b",
      "mdh": "nui";
    },
    "prod_merchant": {
      "prod_delivery": "Scheduled",
      "site": 45
    }
  },
]

My code:

let prod_delivery = req.param('prod_delivery');
console.log(prod_delivery) // Express
GlobalServices.isDisabledAddToCart(filteredProductList, filters)
    .then(function(updatedProductList) //Under updatedProductList that whole array is coming
        {
            var output = updatedProductList.filter(function(x) {
                return x.prod_merchant.prod_delivery == prod_delivery.prod_delivery
            });

            console.log("output", output)
        }

Output: output []

Basically, I want to get all the product details on the basis of prod_delivery from the array.

Upvotes: 0

Views: 49

Answers (1)

chrwahl
chrwahl

Reputation: 13125

You can use filter for that:

var products = [{
    "prod": {
      "a": "b",
      "mdh": "nui"
    },
    "prod_merchant": {
      "prod_delivery": "Express",
      "site": 45
    }
  },
  {
    "prod": {
      "a": "b",
      "mdh": "nui"
    },
    "prod_merchant": {
      "prod_delivery": "Scheduled",
      "site": 45
    }
  }
];

var prod_express = products.filter(product => product.prod_merchant.prod_delivery == 'Express');

console.log(prod_express);

Upvotes: 2

Related Questions