如何高效地使用下划线_.pick

时间:2017-09-20 13:57:28

标签: javascript underscore.js

我们如何使用下划线最小化此代码?

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

1 个答案:

答案 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)