2017-09-20 7 views
0

밑줄을 사용하여이 코드를 최소화하려면 어떻게해야합니까?어떻게 효율적으로 밑줄 _.pick을 사용할 수 있습니까?

if (!_.isEmpty(nextprops.category.children)) { 
    let subCategory = []; 

    _.map(nextprops.category.children, (category, key) => { 
     if (!_.isEmpty(category.children)) { 
      _.map(category.children, (subCat, key) => { 
       subCategory.push(subCat); 
      }) 
     } 
    }); 

    this.setState({categories: nextprops.category.children, subCategory: subCategory}); 
} 
+3

이 코드 검토에 속한다고 생각합니다. – Amy

+0

뭐가 문제입니까? "최소화"란 무엇을 의미합니까? – Liam

+0

"효율적"은 일반적으로 "빠른 실행"을 의미합니다. 나는 당신이 "우아한"을 의미하는 것 같아요? –

답변

0

두 가지 방법으로 코드를 줄일 수 있습니다. console.log에서 세 가지 출력을 모두 확인하십시오. https://jsfiddle.net/d2xzuxsj/

var nextprops = {category:{children:[]}} 

//your code 
console.clear(); 
nextprops.category.children = [ 
          {children:["subcat1"]}, {children:["subcat2"]}]; 
if (!_.isEmpty(nextprops.category.children)) { 
    let subCategory = []; 

    _.map(nextprops.category.children, (category, key) => { 
     console.log(category) 
     if (!_.isEmpty(category.children)) { 
      _.each(category.children, (subCat, key) => { 

       subCategory.push(subCat); 
      }) 
     } 
    }); 

console.log(subCategory); 
} 

//Method 1 
let subCategoryA = _.map(nextprops.category.children, function(category, key){ 
    return _.map(category, function(subcategory, key2){ 
     return subcategory 
    }) 
}) 
subCategoryA = _.flatten(subCategoryA) 
console.log(subCategoryA) 


//Method 2 
let subCategoryB = []; 

_.each(nextprops.category.children, function(category, key){ 
    subCategoryB = _.flatten(_.union(subCategoryB, _.map(category, function(subcategory, key2){ 
      return subcategory 
    }))) 
}) 

console.log(subCategoryB) 
+0

답변 해 주셔서 감사합니다. 실제로 도움이됩니다. –