skip to Main Content

I am using a map to ‘filter’ my data, but I’m getting the empty array pieces in the result. How does one alter the code to achieve this?

const WHITE_LIST = ['123', '321'];

const mapped = items.map((item) => ({
  ...item, accounts: item.accounts.map((acc) => ({
    ...acc, products: acc.products.filter((prod) => WHITE_LIST.includes(prod.code))
  }))
}));

console.log(mapped)
<script>
const items =  [
   {
    "accounts": [
      {
        "products": [
          {
            "code": "123",
          }
        ]
      },
      {
        "products": [
          {
            "code": "321",
          }
        ]
      },
      {
        "products": [
          {
            "code": "765",
          }
        ]
      },
      {
        "products": [
          {
            "code": "345",
          }
        ]
      },
    ]
   }
  ];
</script>

Current result:

[
  { products: [ [Object] ] },
  { products: [ [Object] ] },
  { products: [] },
  { products: [] }
]

Expected result:

[
  { products: [ [Object] ] },
  { products: [ [Object] ] }
]

2

Answers


  1. Chosen as BEST ANSWER

    After some hints and tips, I have gotten it to work by adding an extra filter within the existing loops, to filter after the accounts map

    const mapped = items.map((item) => ({
      ...item, accounts: item.accounts.map((acc) => ({
        ...acc, products: acc.products.filter((prod) => WHITE_LIST.includes(prod.code))
      })).filter(i => !!i.products.length)
    }))
    

  2. Just add a filter to end

    const WHITE_LIST = ["123", "321"];
    
    const mapped = items
      .map((item) => ({
        ...item,
        accounts: item.accounts
          .map((acc) => ({
            ...acc,
            products: acc.products.filter((prod) => WHITE_LIST.includes(prod.code)),
          }))
          .filter((x) => x.products.length > 0),
      }))
      .filter((i) => i.accounts.length > 0);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search