如何解决有没有办法过滤另一个数组中的数组中的项目
基本上我有一个对象,里面有一个数组,我有一个这个对象的高级数组。
对象如下。
category: {
name,items: [{
id,name,price,image,}],}
这个数组看起来像:
[{
name: "Category 1",items: [{
id: 1,name: "Item 1 of category 1",price: 12.34,image: "/path/to/image",},{
id: 2,name: "Item 2 of category 1",price: 56.78,image: "/path/to/image2",}]
},{
name: "Category 2",items: [{
id: 3,name: "Item 1 of category 2",price: 87.65,image: "/path/to/image3",{
id: 4,price: 43.21,image: "/path/to/image4",}]
}]
我的问题是,可以搜索 id
,因为我有一个包含所有这些数据的数组。
var price = 0;
const menu = [];
state.user.menu.map((item,k) => {
item.category.items.forEach((itm) => menu.push(itm));
return null;
});
state.user.items.forEach((item) => {
price += menu.filter((itm) => itm.id === item.id)[0].price * item.quantity;
});
这基本上复制对象内部数组中的每个项目并忽略类别名称,因此我只有一个大数组。
对于我现在需要的,我需要将每个项目与类别名称相关联,所以,我不能像现在这样。
基本上,我有一个 Ids
列表,我需要将它们与该数组中的相应类别一起显示。
(Items to search)
[{
timestamp: "123456",userid: "123456",...
id: 1,{
timestamp: "123456",...
id: 3,...
id: 4,}]
(Expected Result)
[{
name: "Category 1",}]
}]
欢迎提出任何建议,谢谢。
解决方法
const data = [
{ name: "Category 1",items: [{ id: 1,name: "Item 1 of category 1",price: 12.34,image: "/path/to/image" },{ id: 2,name: "Item 2 of category 1",price: 56.78,image: "/path/to/image2" }] },{ name: "Category 2",items: [{ id: 3,name: "Item 1 of category 2",price: 87.65,image: "/path/to/image3" },{ id: 4,price: 43.21,image: "/path/to/image4" }] }
];
const getItemsById = (arr = []) => {
// get list of ids to search for
const ids = arr.map(({ id }) => id);
// iterate over list of objects
return data.reduce((list,elem) => {
// get current items with ids
const items = elem.items.filter(({ id }) => ids.includes(id));
// if any found,add element with filtered list
if(items.length > 0) list.push({ ...elem,items });
return list;
},[]);
}
console.log( getItemsById([{ id: 1 },{ id: 3 },{ id: 4 }]) );
这是您要找的吗?
const obj = {
category: {
name: "Test",items: [{
id: 1,name: "Test",price: 50,image: "Test",}],}
}
console.log(obj.category.items[0].id);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。