Check which items in json have a certain value

Asked

Viewed 116 times

0

Hello, how to check which items have value equal to 0 (stock 0), json and loaded by ajax.

$.each(JSON.parse(response), function (i, deliveryTypes) {
      for (var i in deliveryTypes) {
            if(deliveryTypes[i].stockLevel != 0) {
                alert('diferente 0');
            } else {
                alert('igual 0');
            }
            }
    });

goal: if the value of the item (key) "stockLevel" is equal to 0 display a message alerting the user.

json:

{
  "deliveryTypes": [
    {
      "name": "5326",
      "estimatedDays": "7",
      "price": "R$ 1,09",
      "stockLevel": ""
    },
    {
      "name": "3048",
      "estimatedDays": "2",
      "price": "R$ 11,00",
      "stockLevel": "0"
    },
    {
      "name": "MO00001000",
      "estimatedDays": "2",
      "price": "R$ 11,00",
      "stockLevel": "23"
    },
    {
      "name": "3045",
      "estimatedDays": "0",
      "price": "",
      "stockLevel": ""
    }
  ]
}
  • 1

    Add another conditional in if by checking if it is empty: if(deliveryTypes[i].stockLevel != 0 || deliveryTypes[i].stockLevel == "") {

  • 1

    The problem is you’re iterating deliveryTypes while you should iterate on deliveryTypes.deliveryTypes. Its variable deliveryTypes is an object that has a list, not a list.

1 answer

3


Simple, just use method filter()

let json = {
   "deliveryTypes":[
      {
         "name":"5326",
         "estimatedDays":"7",
         "price":"R$ 1,09",
         "stockLevel":""
      },
      {
         "name":"3048",
         "estimatedDays":"2",
         "price":"R$ 11,00",
         "stockLevel":"0"
      },
      {
         "name":"MO00001000",
         "estimatedDays":"2",
         "price":"R$ 11,00",
         "stockLevel":"23"
      },
      {
         "name":"3045",
         "estimatedDays":"0",
         "price":"",
         "stockLevel":""
      }
   ]
}

var array = json.deliveryTypes

var arrayFilter = array.filter(value => {
  return value.stockLevel === "0"
})

if(arrayFilter.length > 0) {
  alert('Existe stockLevel com valor 0');
}

  • 1

    With Arrow Function: array.filter(it => it.stockLevel === "0") :D

  • @Andersoncarloswoss was already editing! It sure gets more readable.

  • @Marconi a detail that I did not specify, I would need to check in which field "name" has stock equal to 0, because when checking need to add the message only in the product with specific "name".

  • 1

    @josecarlos see that in arrayFilter will return you another array with the same fields, but filtered, now just iterate on it.

  • Thanks for the help @Marconi

  • @josecarlos tmj!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.