如何在JavaScript对象中过滤数组中的元素

时间:2014-10-08 02:38:53

标签: javascript

如果我有这样的JavaScript对象:

{"products":
    [
        {
            "id":"6066157707315577",
            "reference_prefix":"BB",
            "name":"BeanieBaby",
            "product_line":false,
            "has_ideas":true
        },
        {
           "id":"6066197229601550",
           "reference_prefix":"BBAGS",
           "name":"BlackBags",
            "product_line":false,
            "has_ideas":false
        }
    ],  
    "pagination": {
        "total_records":4,
        "total_pages":1,
        "current_page":1
    }
}

如何在js中编写一个函数来遍历每一对,只返回has_ideas === true所在的数组元素?

我已经开始这样了但是我被卡住了。显然我是新手。任何帮助表示赞赏。

product: function(mybundle) {

    var json = JSON.parse(mybundle.response.content);
    for(var i = 0; i < json.length; i++) {
        var obj = json[i];

        if (json[i].id === "has_ideas" && json[i].value === true) {
            return json;
        }
       return [];
    } 
}

4 个答案:

答案 0 :(得分:0)

您只需检查该属性即可过滤掉每对:

var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}

var stuff = json.products.filter(function(obj) {
    return obj.has_ideas === true
});

console.log(stuff);

演示:http://jsfiddle.net/bsyk18cb/

答案 1 :(得分:0)

试试这个

product: function(mybundle) {
    var json = JSON.parse(mybundle.response.content);
    for(var i = 0; i < json.length; i++) {
        if(json[i].has_ideas === true){
            return json;
        }
        return [];
    }
}

答案 2 :(得分:0)

你想检查&#34; has_ideas&#34;属性,如果为true,则返回id。

product: function(mybundle) {

    var json = JSON.parse(mybundle.response.content);
    for(var i = 0; i < json.length; i++) {
         if (json[i].has_ideas === true) {
            return json[i].id;
        }
       return [];
    } 
}

答案 3 :(得分:-1)

使用以下代码。

这将返回具有has_ideas=true

的元素数组
var json = "{'products':"+
    "["+
        "{"+
            "'id':'6066157707315577',"+
            "'reference_prefix':'BB',"+
            "'name':'BeanieBaby',"+
            "'product_line':false,"+
            "'has_ideas':true"+
        "},"+
        "{"+
           "'id':'6066197229601550',"+
           "'reference_prefix':'BBAGS',"+
           "'name':'BlackBags',"+
            "'product_line':false,"+
            "'has_ideas':false"+
        "}"+
    "],"+
    "'pagination': {"+
        "'total_records':4,"+
        "'total_pages':1,"+
        "'current_page':1"+
    "}"+
"}";

function filter(){
    var jsonArr = [];
    var gList = eval( "(" + json + ")");
    alert(gList.products.length);
    for(var i=0;i<gList.products.length;i++){
        if(gList.products[i].has_ideas){
            jsonArr.push(gList.products[i]);
        }
    }
    return jsonArr;
}

Demo