根据另一个数组中的值过滤数组

我有一个由对象组成的数组。每个对象都有名称和一个 items 数组。我想根据 id 过滤。


const list = [

 {name: "Bob",

  items: [

   {id: 1, color:"blue"},{id: 2, color:"green"}

  ]

 },

 {name: "Kate",

  items: [

   {id: 3, color:"yellow"},{id: 4, color:"pink"}

  ]

 }, 

 {name: "Fred",

  items: [

   {id: 5, color:"purple"}

  ]

 }

]

如果 id===1,我希望它返回该数组的名称和项目。类似的东西list.filter(listItems => listItems.items.filter(item => item.id === 1))应该返回


name: "Bob",

  items: [

   {id: 1, color:"blue"},{id: 2, color:"green"}

  ]


斯蒂芬大帝
浏览 242回答 3
3回答

萧十郎

如果我理解你的问题,你可以创建一个函数,用于Array.prototype.find返回回调函数返回的数组中的第一个元素true- 在这种情况下,回调可以包含一个 for 循环,当它能够匹配id你时返回 true可以作为函数的另一个参数传入。例如:const list = [{&nbsp; &nbsp; name: "Bob",&nbsp; &nbsp; items: [{&nbsp; &nbsp; &nbsp; id: 1,&nbsp; &nbsp; &nbsp; color: "blue"&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; id: 2,&nbsp; &nbsp; &nbsp; color: "green"&nbsp; &nbsp; }]&nbsp; },&nbsp; {&nbsp; &nbsp; name: "Kate",&nbsp; &nbsp; items: [{&nbsp; &nbsp; &nbsp; id: 3,&nbsp; &nbsp; &nbsp; color: "yellow"&nbsp; &nbsp; }, {&nbsp; &nbsp; &nbsp; id: 4,&nbsp; &nbsp; &nbsp; color: "pink"&nbsp; &nbsp; }]&nbsp; },&nbsp; {&nbsp; &nbsp; name: "Fred",&nbsp; &nbsp; items: [{&nbsp; &nbsp; &nbsp; id: 5,&nbsp; &nbsp; &nbsp; color: "purple"&nbsp; &nbsp; }]&nbsp; }];const filterList = (arr, id) => {&nbsp; return arr.find(el => {&nbsp; &nbsp; for (let i = 0; i < el.items.length; i += 1) {&nbsp; &nbsp; &nbsp; if (el.items[i].id === id) {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; })};console.log(filterList(list, 3))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript