[英]Filter an array of objects upon a value inside an array of objects inside in javascript
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.我想通过检查 items 数组中的属性“name”的值来过滤该对象数组(如果它是“Caret”)。 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?!
我怎样才能在 javascript 中实现这一点?!
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; }
You need to use Array.filter and then loop through your items for a match您需要使用 Array.filter 然后遍历您的项目以进行匹配
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 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
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.