2017-01-18 3 views
0

route.js 파일을 만들었습니다. queryString에 따라 Json 객체를 필터링해야합니다. _.filter 메서드를 사용하면 전체 객체를 응답으로 반환합니다. 사실 나는lodash - 자식을 _filter하고 json 파일에서 모든 부모를 반환하는 방법은 무엇입니까?

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){ 
// 
}); 

답변

0

여기서 문제는 filterByProduct 매개 변수 collproductList 배열에 바인딩되지 않고 productList 배열과 다른 노드를 포함하는 최상위 개체에 바인딩된다는 것입니다. 따라서 대신 coll.productList을 타겟팅해야합니다.

또한 원래 언급 한대로 _.filter (coll.productList)을 사용하면 _.forEach을 사용하는 것보다 더 좋습니다. 왜냐하면 배열을 반복하고 항목을 필터링하기 때문입니다. 대신 filterByProduct이 버전을 시도해보십시오

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

을 마지막으로 productList 노드 플러스 다른 최상위 노드의 필터링 된 버전이 당신의 JSON 데이터 파일과 유사한 개체를 반환, 당신은 얕은에 _.clone 방법을 사용할 수 있습니다 jsonFile 개체를 복제 한 후 productListFilteredProducts 속성을 filterByProduct 함수에서 반환 된 값과 결과 길이가 각각 filterByProduct으로 덮어 씁니다. 다음은 내가 생각해 낸 내용입니다.

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

고맙습니다. 너는 나를 구해 줬어. – Learner17

+0

다행이야. 내가 도울 수있어! – foundling