0

I'm trying to fix my push method in my if statement. My statement looks like this:

var lookup = [];
for(key in JSON){
    var category = JSON[key].Category;
    if(!(category in result)){
        lookup.push(category);
    myVar+=
        "<tr>"+
            "<td align='left'><input type='checkbox' name='comp' id='sub0' class='communication' value='1t'/>"+category+"</td>"
        "</tr>"
    }
}

What I'm trying to do here is if record already exist in lookup value will not be printed out again, if not then will print the value and push in lookup array. My current code is repeating values. I think that my if statement or my push method does not work properly. If anyone can help and tell me what I'm doing wrong I would appreciate. Thank you.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193
  • Where does `result` come from? – Sverri M. Olsen Sep 01 '15 at 12:43
  • 2
    I think you mean if(lookup.indexOf(category) ==-1) ... – mplungjan Sep 01 '15 at 12:44
  • 1
    JSON is the standard object which stores the JSON-related functions. You can't/shouldn't call your own object JSON (at least, not in caps), if that's what you're doing. Also, what does the JSON look like? – Domino Sep 01 '15 at 12:44
  • You should also [avoid using `for...in`](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea#answer-500531). You can use `Object.keys(obj).forEach(function (key) { ... });` instead. – Sverri M. Olsen Sep 01 '15 at 12:46
  • 1
    Thank you all, indexOf is what I needed in my code. Code works right now. – espresso_coffee Sep 01 '15 at 12:48

1 Answers1

1

I think you need Array.prototype.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Script

var lookup = [];
for (key in jsonObject) {
    var category = jsonObject[key].Category;
    if (lookup.indexOf(category) == -1) {
        lookup.push(category);
        myVar +=
            "<tr>" +
            "<td align='left'><input type='checkbox' name='comp' id='sub0' class='communication' value='1t'/>" + category + "</td>"
        "</tr>"
    }
}
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 1
    Thank you, this works perfectly fine. My values did not repeat multiple times. Can you tell me one more time why I have to use indexOf in this case and why should be equal -1? – espresso_coffee Sep 01 '15 at 12:48
  • 1
    @user3023588 The `indexOf()` method returns the first index of element if found otherwise `-1`. – Satpal Sep 01 '15 at 12:49