程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了有没有办法过滤另一个数组中的数组中的项目大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决有没有办法过滤另一个数组中的数组中的项目?

开发过程中遇到有没有办法过滤另一个数组中的数组中的项目的问题如何解决?下面主要结合日常开发的经验,给出你关于有没有办法过滤另一个数组中的数组中的项目的解决方法建议,希望对你解决有没有办法过滤另一个数组中的数组中的项目有所启发或帮助;

基本上我有一个对象,里面有一个数组,我有一个这个对象的高级数组。

对象如下。

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);

大佬总结

以上是大佬教程为你收集整理的有没有办法过滤另一个数组中的数组中的项目全部内容,希望文章能够帮你解决有没有办法过滤另一个数组中的数组中的项目所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: