Reputation: 285
I am fetching an array of objects as following :
const data =
[ { id: 0, company: 'nike', items: [{ id: 0, name: 'caret', price: 100}] }
, { id: 1, company: 'adidas', items: [{ id: 1, name: 'mobile phone', price: 300}] }
]
I want to filter that array of objects by checking the value of the property "name" inside the items array if it is "Caret" or not. If yes, I want to return the same array of objects with all its content but filtered. Which means, it will filter out the object whose item's name is not caret. How can I achieve this in javascript?!
Upvotes: 1
Views: 172
Reputation: 22265
I suppose you are looking for that ?
const data =
[{ id: 0, company: 'nike', items: [{ id: 0, name: 'caret', price: 100}]}
,{ id: 1, company: 'adidas', items: [{ id: 1, name: 'mobile phone', price: 300}]}
]
const filterName = (arr, name)=>arr.filter(el=>el.items.some(x=>x.name==name))
onlyCaret = filterName(data,'caret')
console.log( onlyCaret[0].company ) // nike
console.log( onlyCaret ) // row 0 with { ... company: 'nike' ..}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 156
You need to use Array.filter and then loop through your items for a match
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const data = [
{
id:0,
company: "nike"
items:[
name: "caret",
price:100
]
},
{
id:1,
company: "adidas"
items:[
name: "mobile phone",
price: 300
]
},
]
const filteredCompanies = data.filter((company)=>{
company.items.forEach((item)=>{
if(item.name === "nike") return true
})
})
Upvotes: 1