我有一個對象數組,我試圖通過抓取第一個子對象來匹配我給它的某個對象。所以,我的目標看起來像這樣:Javascript,返回匹配的第一個(子)對象
const filteredVariants = [
{
name: "Test0",
images: [
{
name: "test0img1",
shot_type: "swatch"
}]
}, {
name: "Test1",
images: [
{
name: "test1img1",
shot_type: "product"
},
{
name: "test1img2",
shot_type: "product"
}]
}]
所以我所希望做的是通過這個對象看,特別是內images
,發現有shot_type: "product"
的第一個對象,並返回。所以,在這種情況下,我試圖讓它回到我:
{
name: "test1img1",
shot_type: "product"
}
這是我到目前爲止有:
const firstProductImage = _.find(filteredVariants, _.flow(
_.property('images'),
_.partialRight(_.some, { shot_type: 'product' })
));
這部分是存在的方式,除了它返回的整個父對象,當我只需要孩子的圖像對象。我試着跑過地圖和過濾器,但這些方法並不像這個那樣乾淨。我想知道是否有辦法告訴lodash在這種情況下只返回匹配{ shot_type: 'product' }
的第一個子節點。
我使用lodash,但如果這是可能的普通的JavaScript,這將是很好的。謝謝!