过滤多维 JSON 数组 [英] filter multi-dimension JSON arrays

查看:40
本文介绍了过滤多维 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 JSON 详细信息:

Here is the JSON details:

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"
                }]
            }
        }
    }
}

我尝试过滤数组以具有包含 da 模式的 shop.

I've tried to filter the array to have shop which contain da pattern.

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

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

=========UPDATE=============================================================

刚刚发现,此代码有效.但它返回如下内容:

Just figured out, this code works. But it returns something like this:

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

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

ideally, I'd like to get something like this:

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

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

推荐答案

你可以这样做

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;
}, []);

这篇关于过滤多维 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆