Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ WHERE clause equivalent in javascript

I am looking to extract information from my javascript array `lstObj' that looks like this:

[
  {
    "DealerId": "1",
    "Type": "Apple,Orange"
  },
  {
    "DealerId": "2",
    "Type": "Mango"
  },
  {
    "DealerId": "3",
    "Type": "Mango"
  }
]

I want to check if there is an item that has Type = Mango and DealerID not = 2. In C# linq I would do something like this:

if(lstObj.Any(x=>x.Type.Split(',').Contains("Mango") && x.DealerID != 2))
{
      //Do something
}

How can I achieve the same using javascript?

like image 623
Huma Ali Avatar asked Jul 16 '19 21:07

Huma Ali


2 Answers

This should do. If there is no item it will return empty array, otherwise it will return items.

let result = lstObj.filter(dealer =>  dealer.Type.split(',').includes('Mango') && dealer.DealerId != 2);

let lstObj = [
  {
    "DealerId": "1",
    "Type": "Apple,Orange"
  },
  {
    "DealerId": "2",
    "Type": "Mango"
  },
  {
    "DealerId": "3",
    "Type": "Mango"
  }
]

let result = lstObj.filter(dealer => dealer.Type.split(',').includes('Mango') && dealer.DealerId != 2)

console.log(result)
like image 79
SimoMatavulj Avatar answered Sep 20 '22 01:09

SimoMatavulj


You can use some:

var result= array.some(function (item) {
    return  item.Type.split(",").inlcudes("Mango") && item.DealerID != 2;
});
like image 37
octavioccl Avatar answered Sep 19 '22 01:09

octavioccl