假设我有这样的数据:
const clowder = {
count: 3,
cats: [
{name: 'Moo', color: 'grey'},
{name: 'Sophie', color: 'black'},
{name: 'Tipper', color: 'black'}
]
}
at()
将单个猫从 clowder 中取出:
>> _.at(clowder, 'cats[0].name')
'Moo'
>> _.at(clowder, ['cats[1].name', 'cats[2].name'])
['Sophie', 'Tipper']
有没有办法指定像这样的简单语法来映射所有猫的路径,而不是返回一个数组?
>> _.at(clowder, 'cats[].name') // doesn't work
['Moo', 'Sophie', 'Tipper']
这是一个简化的例子。真正的用例是 3+ 级映射。考虑:
clowder.cats.some(cat =>
cat.foods.some(food =>
food.ingredients.some(ingredient =>
ingredient.includes('chicken'))
)
)
)
对
_.at(clowder, 'cats[].foods[].ingredients[]')
.some(ingredient => ingredient.includes('chicken'))
就我个人而言,我发现第二个版本在 3 个级别上更容易编写和阅读,只有在 4+ 时更容易(是的,我在野外看到过。)