简体   繁体   中英

filter an object of an array of an object

 Objects:[
  {id:'a',
   owner: 'b',
   products:[{productId:'a1',name:'b1'},{productId:'a2',name:'b2'}]
   date: '2-2'},

  {id:'e',
   owner: 'f',
   products:[{productId:'a3',name:'b3'},{productId:'a4',name:'b4'}]
   date: '1-1'}
 ]

In above example, how do I get the second object by the value of name:'b3'? The name is an attribute of products array and products is an attribute of objects array. I'll appreciate if someone can help me out.

To search for items based on the "name" property of the products list, you can do the following:

 const Objects = [ {id:'a', owner: 'b', products:[{productId:'a1',name:'b1'},{productId:'a2',name:'b2'}], date: '2-2'}, {id:'e', owner: 'f', products:[{productId:'a3',name:'b3'},{productId:'a4',name:'b4'}], date: '1-1' } ] const hasProductsByName = (products) => { return products.some(product => product.name == searchValue); } const searchValue = "b3"; const result = Objects.filter(obj => hasProductsByName(obj.products)); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM