【问题标题】:lodash - how to _.filter the childs and return all parents from a json file?lodash - 如何 _.filter 孩子并从 json 文件中返回所有父母?
【发布时间】:2017-01-18 06:44:56
【问题描述】:

我已经创建了 route.js 文件。基于 queryString 它必须过滤 Json 对象。当我使用 _.filter 方法时,它会返回整个对象作为响应。实际上我想过滤该产品列表节点并将其余节点包括在内作为响应 请帮助我..在此先感谢...

这是代码..

JSON 文件

{
    "productList": [
        {
            "productName": "xyz",
            "productType": "mobile"
        },
        {
            "productName": "xyz",
            "productType": "mobile"
        },
        {
            "productName": "xyz",
            "productType": "mobile"
        }
    ],
    "totalProducts": 3,
    "FilteredProducts": 0,
    "test1": 11,
    "test11": 12,
    "test33": 13
}

route.js

var filterByProduct = function(coll, productType){
    return  _.forEach(coll, function(o){
        return _.find(o, function(item){
        });
    });
};
var queryString = function(req, res, next) {
    if (req.query.productType ) {
        var stringObj = JSON.stringify(filterByProduct(jsonFile, req.query.productType),null,4);
        res.end(stringObj);
    } else if (req.query !== {}) {
        var stringObj = JSON.stringify(jsonFile,null,4);
        res.end(stringObj);
    } else {
        res.end('Not a Query String');
    }
}

router.get('/test', queryString, function(req,res){
//
});

【问题讨论】:

    标签: javascript json node.js express lodash


    【解决方案1】:

    这里的问题是filterByProduct 参数coll 没有绑定到productList 数组,而是包含productList 数组以及其他节点的顶级对象。所以你应该定位coll.productList

    此外,使用您最初提到的_.filter(在coll.productList)比使用_.forEach 更好,因为它遍历数组并过滤项目。试试这个版本的filterByProduct

    var filterByProduct = function(coll, productType){
        return _.filter(coll.productList, function(o) {
            return o.productType === productType;
        })
    };
    

    最后,要返回一个类似于您的 JSON 数据文件的对象,其中包含过滤版本的 productList 节点以及其他顶级节点,您可以使用 _.clone 方法浅克隆您的 jsonFile 对象并然后分别用filterByProduct 函数返回的值和filterByProduct 的结果长度覆盖productListFilteredProducts 属性。这是我想出的:

    if (req.query.productType) {
        var stringObj = _.clone(jsonFile);
        stringObj.productList = filterByProduct(jsonFile, req.query.productType);
        stringObj.FilteredProducts = stringObj.productList.length;
        res.end(stringObj);
    }
    

    【讨论】:

    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多