【问题标题】:Filtering fetched data过滤获取的数据
【发布时间】:2022-11-26 14:55:30
【问题描述】:

我有一个过滤器对象。

filters = {color: 'black', size: '40'}

我想返回经过过滤的数据数组。这是我的数据示例:

data = [  
  [ 
    id: 1,
    name: "Good Engine001"
    categories: ['machine'],
    color: ['Black', 'white'],
    size: [30, 40, 50]
  ],
  

[ 
    id: 2,
    name: "Good Plane"
    categories: ['machine', 'plane'],
    color: ['Grey', 'white'],
    size: [10, 30, 50]
  ],

[ 
    id: 3,
    name: "Good Chair001"
    categories: ['furniture', 'chair'],
    color: ['Brown', 'Black'],
    size: [3, 5, 40]
  ]
];
filteredProducts = data.filter((item) =>
    Object.entries(filters).every(([key, value]) =>
        item[key].includes(value)
    )

我被困在这里了。我试图将过滤后的产品设置为等于与我的过滤器对象中提供的值匹配的少数条目。我究竟做错了什么?

我期待这个:

filteredProducts = [
        
[ 
    id: 1,
    name: "Good Engine001"
    categories: ['machine'],
    color: ['Black', 'white'],
    size: [30, 40, 50]
  ],


[ 
    id: 3,
    name: "Good Chair001"
    categories: ['furniture', 'chair'],
    color: ['Brown', 'Black'],
    size: [3, 5, 40]
  ]

];

但我得到了相同的数据。

【问题讨论】:

  • 您的数组不是有效的 javascript。

标签: javascript arrays algorithm filter


【解决方案1】:

颜色名称在数据中是大写的,而不是在过滤器中。 '40' 是过滤器中的字符串文字,而它是数据中的数字。 而且你的数据应该是这样的,每个项目周围都有花括号:

const data = [
      {
        id: 1,
        name: "Good Engine001",
        categories: ['machine'],
        color: ['Black', 'white'],
        size: [30, 40, 50]
      },
      {
        id: 2,
        name: "Good Plane",
        categories: ['machine', 'plane'],
        color: ['Grey', 'white'],
        size: [10, 30, 50]
      },
      {
        id: 3,
        name: "Good Chair001",
        categories: ['furniture', 'chair'],
        color: ['Brown', 'Black'],
        size: [3, 5, 40]
      }
    ];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多