0

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.

14
  • What's the value of prod_delivery? Commented Aug 8, 2021 at 12:05
  • In the array I have mentioned the value of prod_delivery , which is prod_delivery: "Express" or prod_delivery: "Scheduled" Commented Aug 8, 2021 at 12:07
  • I'm taking about let prod_delivery = req.param('prod_delivery'); Commented Aug 8, 2021 at 12:07
  • 1
    So if prod_delivery is a string, then prod_delivery.prod_delivery is undefined. No wonder you get an empty array. Commented Aug 8, 2021 at 12:12
  • 1
    Replace x.prod_merchant.prod_delivery == prod_delivery.prod_delivery with x.prod_merchant.prod_delivery == prod_delivery. That should do it. Commented Aug 8, 2021 at 12:15

1 Answer 1

2

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

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

2 Comments

Maybe with this answer one considers providing a case insensitive search/filter approach in order to solve the true/real issue the OP was experiencing (express vs Express). After all the OP's filter method was/is implemented correctly for case sensitivity / value equality.
@PeterSeliger I can see that from the comments, but I think that was more a bug then af feature. In any case OP could compare the lower case strings, like: product.prod_merchant.prod_delivery.toLowerCase() == 'Express'.toLowerCase()

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.