为了账号安全,请及时绑定邮箱和手机立即绑定

javascript过滤数组内对象内的数组

javascript过滤数组内对象内的数组

一只名叫tom的猫 2021-12-02 16:43:56
第一个帖子!我已经做了一些搜索,找到并尝试了一些接近我的问题的答案,但没有一个完全匹配。我有一个对象数组:const kids = [  { name: 'alice',     age: 13,     pets: [      { type: 'fish', pet_name: 'nemo' },      { type: 'cat', pet_name: 'snuffles'},      { type: 'cat', pet_name: 'pixel'}    ]  },  { name: 'bob',     age: 7,    pets: [      { type: 'dog', pet_name: 'rover' }    ]   },  { name: 'chris',    age: 15,    pets: [      { type: 'cat', pet_name: 'fluffy' },      { type: 'donkey', pet_name: 'eeyore' }    ]  }]我想得到所有拥有猫的孩子,使用高阶函数而不是循环。我想要的结果是cat_owners = [               { name: 'alice', age: 13,                 pets: [ { type: 'cat', pet_name: 'snuffles' },                        { type: 'cat', pet_name: 'pixel' } ]              },              { name: 'chris', age: 15,                 pets: [ {  type: 'cat', pet_name: 'fluffy' } ] }             ]我已经尝试了过滤器、forEach、find 的各种组合,例如const cat_owners = kids.filter(kid => kid.pets.find(pet => pet.type === 'cat') )const kids = [  { name: 'alice',     age: 13,     pets: [      { type: 'fish', pet_name: 'nemo' },      { type: 'cat', pet_name: 'snuffles'},      { type: 'cat', pet_name: 'pixel'}    ]  },  { name: 'bob',     age: 7,    pets: [      { type: 'dog', pet_name: 'rover' }    ]   },  { name: 'chris',    age: 15,    pets: [      { type: 'cat', pet_name: 'fluffy' },      { type: 'donkey', pet_name: 'eeyore' }    ]  }];const cat_owners = kids.filter(kid => kid.pets.find(pet => pet.type === 'cat'));console.log(cat_owners);但这也返回了爱丽丝的鱼和克里斯的驴——我只想要猫。我已经成功地把自己弄糊涂了,我只是找不到正确的调用来让我的爱猫者和他们的猫,我已经为这个“简单”的问题苦苦挣扎了几个小时了……所以我的问题是“我如何达到这个预期的结果?”
查看完整描述

3 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

这会有所帮助

kids.filter((x) => x.pets.filter((y) => y.type === 'cat').length > 0);


查看完整回答
反对 回复 2021-12-02
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

疯狂的单线,有点工作:

const catLovers = kids.map(k => k.pets.some(p => p.type === 'cat') ? {...k, pets: k.pets.filter(p => p.type === 'cat')} : null).filter(k => k)

它实现了以下算法:“对于每个至少有一只猫的孩子,只用猫创建新的数组记录(否则为 null),然后过滤掉空记录”。

可能会添加格式以提高可读性,但在那之后它不会是单行的:)


查看完整回答
反对 回复 2021-12-02
?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

如果我理解清楚,你只想要有猫的孩子,但在他们的宠物清单中,只有猫。


这是我的建议:


const kids = [

  { name: 'alice', 

    age: 13, 

    pets: [

      { type: 'fish', pet_name: 'nemo' },

      { type: 'cat', pet_name: 'snuffles'},

      { type: 'cat', pet_name: 'pixel'}

    ]

  },

  { name: 'bob', 

    age: 7,

    pets: [

      { type: 'dog', pet_name: 'rover' }

    ] 

  },

  { name: 'chris',

    age: 15,

    pets: [

      { type: 'cat', pet_name: 'fluffy' },

      { type: 'donkey', pet_name: 'eeyore' }

    ]

  }

];


const owners = [];

const type = 'cat';


kids.forEach(kid => {

  kid.pets = kid.pets.filter(pet => pet.type === type);

  if (kid.pets.length)

    return owners.push(kid);

});


console.log(owners);


查看完整回答
反对 回复 2021-12-02
  • 3 回答
  • 0 关注
  • 276 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信