2

I'm displaying data from an array of objects but I want to filter the results so that I display only the names of those objects that have a winner property with a value of 1.

<script>
$(document).ready(function () {
    var json = [
        {"name":"Name 1","winner":"1"},
        {"name":"Name 2","winner":"0"},
        {"name":"Name 3","winner":"1"},
        {"name":"Name 4","winner":"1"},
        {"name":"Name 5","winner":"0"},
    ];

    var li;
    for (var i = 0; i < json.length; i++) {
        li = $('<li/>');
        li.append(json[i].name);
    $('#feed').append(li);
    }
});
</script>

HTML should be like this (showing only results when winner is true, winner=1)

<ul id="feed" >
    <li>Name 1</li>
    <li>Name 3</li>
    <li>Name 4</li>
</ul>
8
  • 3
    Is that really a <font> tag ? Commented Jul 26, 2014 at 21:22
  • 2
    That's not JSON: json.org Commented Jul 26, 2014 at 21:25
  • with the exception of the comma after the last object, yes it is. Commented Jul 26, 2014 at 21:28
  • @Brad.Smith - It certainly isn't, it's a javascript object, but in this case it doesn't really matter. Commented Jul 26, 2014 at 21:31
  • 1
    @Brad.Smith: Semantics and using the right terminology are very important. Otherwise, how should we be able to communicate? The problem has nothing to do with JSON, it's a pure JS problem. Commented Jul 26, 2014 at 21:40

4 Answers 4

4

You may try using an if statement:

for (var i = 0; i < json.length; i++) {
    if (json[i].winner === '1') {
        li = $('<li/>');
        li.append("<font size='+1'>" + json[i].name + "</font>");
        $('#feed').append(li);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Just add a condition in the loop

for (var i = 0; i < json.length; i++) {
    if (json[i].winner === "1") {

        $('<li />', {text : json[i].name}).appendTo('#feed');

    }
}

FIDDLE

Comments

3

You have to add an if statement to check if winner is equal to 1:

var json = [
        {"name":"Name 1","winner":"1"},
        {"name":"Name 2","winner":"0"},
        {"name":"Name 3","winner":"1"},
        {"name":"Name 4","winner":"1"},
        {"name":"Name 5","winner":"0"},
    ];

    var li;
    for (var i = 0; i < json.length; i++) {
    if(json[i].winner == "1"){ //add this
        li = $('<li/>');
        li.append("<font size='+1'>" + json[i].name + "</font>");
    $('#feed').append(li);
    }
 }

fiddle

Comments

3

Try this:

    var ul = $('ul#feed');
    for (var i = 0; i < json.length; i++) {
        if (json[i].winner == 1) {
            ul.append("<li>" + json[i].name + "</li>");
        }
    }

Working fiddle.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.