检查对象是否具有具有特定值的属性

时间:2014-07-26 21:20:26

标签: javascript jquery html

我正在显示来自对象数组的数据,但我想过滤结果,以便只显示那些name属性值为{winner的对象的1 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应如下所示(仅在获胜者为真时显示结果,winner = 1

<ul id="feed" >
    <li>Name 1</li>
    <li>Name 3</li>
    <li>Name 4</li>
</ul>

4 个答案:

答案 0 :(得分:4)

您可以尝试使用if声明:

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);
    }
}

答案 1 :(得分:3)

只需在循环中添加条件

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

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

    }
}

FIDDLE

答案 2 :(得分:3)

您必须添加一个if语句来检查获胜者是否等于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

答案 3 :(得分:3)

试试这个:

    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.