【问题标题】:How to filter an array inside an array by an array field?如何通过数组字段过滤数组内的数组?
【发布时间】:2022-11-19 23:57:19
【问题描述】:

当我想通过数组过滤数组内的数组时,我遇到了一个问题。请看例子-

const array1 = [
    {
        name: "this is name1",
        products: [
            { id: "4" },
            { id: "2" },
        ]
    },
    {
        name: "this is name2",
        products: [
            { id: "2" },
            { id: "1" }
        ]
    }
]

const array2 = [
    { id: "1", refund: true },
    { id: "2", refund: false },
    { id: "3", refund: true },
    { id: "4", refund: false}
]

在这里,我必须过滤array1 products 字段。在 array1 products 中提交了一个带有 id 的数组。我必须通过按 id 从 array2 中搜索相同的对象来过滤此产品字段,然后在退款为真时进行过滤。

从这个例子我需要结果 -

const array1 = [
    {
        name: "this is name2",
        products: [
            { id: "1" }
        ]
    }
]

结果我们只能看到这个数组中的一个对象。因为从array1开始,在对象的product filed中有两个id 42。从 array2 我们可以看到 id 42 的退款 false。这就是为什么 array1 删除第一个对象。

在第二个对象中,我们可以看到产品字段包含两个 id 21。从array2我们可以看到退款是false id 2 但退款是true id 1。因此对于 id 1 refund 是 true 这就是它留在产品数组中的原因。

请帮我。我希望我能解决我的问题。

【问题讨论】:

  • 问题是什么?

标签: javascript


【解决方案1】:

您可以组合使用 filtermapreduce 等数组方法来获取结果。

const array1 = [
  {
    name: 'this is name1',
    products: [{ id: '4' }, { id: '2' }],
  },
  {
    name: 'this is name2',
    products: [{ id: '2' }, { id: '1' }],
  },
];

const array2 = [
  { id: '1', refund: true },
  { id: '2', refund: false },
  { id: '3', refund: true },
  { id: '4', refund: false },
];

// Transforms array2 to { 1: { id: 1, refund: true }, 2: ...}  
const array2ToMap = array2.reduce((map, item) => {
    map[item.id] = item
    return map
}, new Map());

const result = array1
  .map(item => {
    // Filters only the products that have refund as `true`
    const filteredProducts = item.products.filter(
      product => array2ToMap[product.id]?.refund
    );
    return { ...item, products: filteredProducts };
  })
  // Only select items which have at least 1 filtered products
  .filter(item => item.products.length > 0);

console.log(result);

【讨论】:

  • 您好,我更新了我的问题以再做一件事。你能更新你的答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 2021-11-06
  • 1970-01-01
  • 2011-10-28
  • 2019-08-22
  • 2017-04-12
  • 2015-03-24
相关资源
最近更新 更多