filter multi-dimension JSON arrays

爷,独闯天下 提交于 2019-12-11 19:38:32

问题


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

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

回答1:


You can do this

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


来源:https://stackoverflow.com/questions/18517004/filter-multi-dimension-json-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!