0

这是 JSON 详细信息:

var array={
    "app": {
        "categories": {
            "cat_222": {
                "id": "555",
                "deals": [{
                    "id": "73",
                    "shop": "JeansWest"
                },
                {
                    "id": "8630",
                    "shop": "Adidas"

                },
                {
                    "id": "11912",
                    "shop": "Adidas"
                }]
            },
            "cat_342": {
                "id": "232",
                "deals": [{
                    "id": "5698",
                    "shop": "KFC"
                },
                {
                    "id": "5701",
                    "shop": "KFC"
                },
                {
                    "id": "5699",
                    "shop": "MC"
                }]
            }
        }
    }
}

我试图过滤数组以shop使其包含da模式。

var filted = _.filter(array.app.categories,function(item) {
    return _.any(item.deals,function(c) {
        return c.shop.indexOf('da') != -1;
    });
});

=========更新======================================== ======================

刚刚发现,这段代码有效。但它返回如下内容:

[{
"id": "555",
"deals": [{
    "id": "73",
    "shop": "JeansWest"
}, {
    "id": "8630",
    "shop": "Adidas"
}, {
    "id": "11912",
    "shop": "Adidas"
}]
}]

理想情况下,我想得到这样的东西:

[{
"id": "555",
"deals": [{

    "id": "8630",
    "shop": "Adidas"
}, {
    "id": "11912",
    "shop": "Adidas"
}]
}]
4

1 回答 1

1

你可以这样做

var filted = _.reduce(array.app.categories, function (memo, item) {
    var result = _.filter(item.deals, function (c) {
        return c.shop.indexOf('da') != -1;
    });

    if (result.length > 0) {
        var newResult = {};
        newResult.deals = result;
        newResult.id = item.id;
        memo = _.union(memo, newResult);
    }

    return memo;
}, []);
于 2013-08-30T00:57:12.097 回答