使用 lodash 进行深度数组选择
Deep array selection with lodash
我几乎没有使用过 lodash,现在我正在尝试使用它来完成一个简单的任务。
我有一个可行的解决方案,但它看起来很复杂,我想知道使用库实用程序是否有一个简单的 shorthand 任务。
items
是一个对象数组,如下所示:
{
id: ‘string’,
val_1: ‘string’,
val_2: ‘string’,
components: array of: {
val_3: ‘string’,
val_4: ‘string’,
types: array of strings
}
}
我想要 select 一个其组件数组包含 有效类型 的对象。
有效类型由我在大约 10 个字符串的数组中定义。这是我的解决方案:
var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
var allowed = true;
_.forEach(item.components, (component) => {
// Remove valid types. What's left should be empty.
_.pullAll(component.types, validTypes);
allowed = allowed && _.isEmpty(component.types);
})
return allowed;
});
如前所述,我想知道如何改进,我觉得我没有正确使用 lodash。
首先,_.pullAll
改变你的对象,不应该被使用。
您可以改用_.every
和_.some
,一旦发现不可接受的值,这将停止循环。
var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
return _.every(item.components, (component) => { // all components must be valid
return _.isEmpty(_.difference(component.types, validTypes)); // there shouldn't be any types that are not in the valid
}
}
我几乎没有使用过 lodash,现在我正在尝试使用它来完成一个简单的任务。
我有一个可行的解决方案,但它看起来很复杂,我想知道使用库实用程序是否有一个简单的 shorthand 任务。
items
是一个对象数组,如下所示:
{
id: ‘string’,
val_1: ‘string’,
val_2: ‘string’,
components: array of: {
val_3: ‘string’,
val_4: ‘string’,
types: array of strings
}
}
我想要 select 一个其组件数组包含 有效类型 的对象。 有效类型由我在大约 10 个字符串的数组中定义。这是我的解决方案:
var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
var allowed = true;
_.forEach(item.components, (component) => {
// Remove valid types. What's left should be empty.
_.pullAll(component.types, validTypes);
allowed = allowed && _.isEmpty(component.types);
})
return allowed;
});
如前所述,我想知道如何改进,我觉得我没有正确使用 lodash。
首先,_.pullAll
改变你的对象,不应该被使用。
您可以改用_.every
和_.some
,一旦发现不可接受的值,这将停止循环。
var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
return _.every(item.components, (component) => { // all components must be valid
return _.isEmpty(_.difference(component.types, validTypes)); // there shouldn't be any types that are not in the valid
}
}