[英]How can I use underscore _.pick in my if efficiently
我们如何使用下划线最小化此代码?
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});
}
您可以减少两种方法的代码。 检查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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.