D
D
drtvader2016-03-30 12:31:11
JavaScript
drtvader, 2016-03-30 12:31:11

How to check JSON for a specific string?

Hi, how can I check JSON for the presence of a certain element.
For example, I have

{
            "id": "4",
            "name": "Weissgold-Verlobungsring mit Diamanten",
            "image": "/images/content/white-gold1.jpg",
            "oldprice": "14 500 €",
            "newprice": "16 100 €",
            "discount": "-10%"
        },
       {
            "id": "5",
            "name": "Gold-Verlobungsring mit Diamanten",
            "image": "/images/content/white-gold2.jpg",
            "oldprice": "110 500 €",
            "newprice": "16 100 €",
            "hit": "hit"
        },
        {
            "id": "6",
            "name": "Ring zur Verlobung mit Diamanten",
            "image": "/images/content/white-gold3.jpg",
            "oldprice": "110 500 €",
            "newprice": "16 100 €",
            "new": "new"
        },
        {
            "id": "7",
            "name": "Ring zur Verlobung mit Diamanten",
            "image": "/images/content/white-gold1.jpg",
            "oldprice": "110 500 €",
            "newprice": "16 100 €"
        },
        {
            "id": "8",
            "name": "Ring zur Verlobung mit Diamanten",
            "image": "/images/content/white-gold3.jpg",
            "oldprice": "110 500 €",
            "hit": "hit"
        }

There is the last line discount, hit, new, how to check its presence and make a conclusion?
I tried like this:
if (parseInt(data.discount) > 0) {
    html = '<div class="b-sale b-sale--list-product">' + data.discount + '</div>';
  }
else (parseInt(data.hit) > 0) {
   html = '<div class="b-sale b-sale--hit">' + data.hit+ '</div>';
}
but the option doesn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-03-30
@drtvader

Firstly, the if is omitted after the else to check another condition
Secondly, parseInt("-10%") will be -10, which, when compared > 0, will give false
Thirdly, parseInt("hit") will be NaN, which, if any comparison with anything, including c NaN will give a false
Correct check something like this:

if('discount' in data && parseInt(data.discount) < 0) {
  //...
} else if(data.hit === 'hit') {
  //...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question