日期:2014-05-16  浏览次数:20458 次

关于筛选json并生成新的json的问题。
有一json数据如下:
JScript code

var products = [{
    id: "1001",
    name: "a",
    cate: "x"
},
{
    id: "1002",
    name: "b",
    cate: "x"
},
{
    id: "1003",
    name: "c",
    cate: "x"
},
{
    id: "1004",
    name: "c",
    cate: "y"
}];



如何用js筛选出所有cate=x的数据并生成性的json如下:
JScript code
var products = [{
    id: "1001",
    name: "a",
    cate: "x"
},
{
    id: "1002",
    name: "b",
    cate: "x"
},
{
    id: "1003",
    name: "c",
    cate: "x"
}];



------解决方案--------------------
JScript code

    var products=[{id:"1001",name:"a",cate:"x"},{id:"1002",name:"b",cate:"x"},{id:"1003",name:"c",cate:"x"},{id:"1004",name:"c",cate:"y"}];
    var arr = [];
    for(var i = 0, len = products.length; i < len; i++){
        if( products[i].cate == 'x' ){
            arr.push(products[i])
        }
    }
    alert(arr)