【问题标题】:How to filter out nested array of obj [duplicate]如何过滤掉obj的嵌套数组[重复]
【发布时间】:2021-10-21 23:06:54
【问题描述】:

这是我的数据:

{
  "productGroups": [
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
      ]
    },
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
      ]
    },
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
      ]
    }
  ]
}

如果没有 selectedProducts.id,我想删除数组元素

所以结果应该是:

{
  "productGroups": [
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
      ]
    }
  ]
}

这是我尝试过的:

const filteredData = {
  productGroups: data.productGroups.map(productGroup => {
    const selectedProduct = productGroup.selectedProducts?.filter(product => product.id);
    return selectedProduct;
  }),
};

我的结果是错误的,我得到的结果是空数组:

{
  "productGroups": [
    [
      { "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e9a5eb13b4126a9e07e37" }],
    [],
    []
  ]
}

【问题讨论】:

  • 为什么选择.map()?你看过Array的其他方法吗?

标签: javascript reactjs ecmascript-6


【解决方案1】:

let data = {
  "productGroups": [
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
      ]
    },
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
      ]
    },
    {
      "selectedProducts": [
        { "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
      ]
    }
  ]
};


const filteredData = {
  productGroups: data.productGroups.filter(productGroup => {
    const selectedProduct = productGroup.selectedProducts.filter(product => product.id);
      return selectedProduct.length;
  }),
};


console.log(JSON.stringify(filteredData))

【讨论】:

  • 如果selectedProduct 数组中包含有和没有 id 的元素,它们仍将被包含在内。
  • 您能解释一下 selectedProduct.length 的工作原理吗? @norbert.mate
  • 由于您的内部filter 实际上并没有过滤任何内容,因此仅使用some() 会更有效。有些会提前退出,而过滤器会根据需要迭代所有元素。 productGroups: data.productGroups.filter(({ selectedProducts }) => selectedProducts.some(({ id }) => id !== undefined)),
  • @pilchard 我明白你的意思,这是有道理的,但 Emilis 要求:“如果没有 selectedProducts.id,请删除数组元素”
  • @Emilis 如果没有具有 id 的元素,则数组将为空,因此长度将为 0。数组过滤器通过检查返回值是否为真/假来工作。在这种情况下,0 将被评估为假。
【解决方案2】:

我会这样做:

const filteredData = {
  productGroups: data.productGroups.filter(productGroup => {
     return (productGroup.selectedProducts.filter((product) => (product.id !== undefined && product.id != '') ? true: false)).length;
  }),
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 2019-10-30
    • 1970-01-01
    • 2018-03-21
    • 2022-07-13
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多