简体   繁体   中英

Trying to filter out items from a deeply nested sub array of objects, keep getting property doesn't exist and empty array response

I have an array of objects each with its own subarray of objects.

I'm trying to filter through each of the subarrays and remove any element that doesn't match the condition expired === false but I keep getting an error that says: Property 'expired' does not exist on type '{ name: string; expired: boolean; }[]'.ts(2339) Property 'expired' does not exist on type '{ name: string; expired: boolean; }[]'.ts(2339) Property 'expired' does not exist on type '{ name: string; expired: boolean; }[]'.ts(2339) empty array and I'm not sure what I'm doing wrong.

Codesandbox

My function is this:

result.filter(files => files.files.expired === false)

Here's what the parent object structure looks like:

const result = 
[
  {
    type: "Documents",
    files: [
      {
        name: "file_1",
        expired: true
      },
      {
        name: "file_2",
        expired: false
      },
      {
        name: "file_3",
        expired: false
      },
      {
        name: "file_4",
        expired: true
      },
      {
        name: "file_5",
        expired: false
      }
    ]
  },
  {
    type: "Images",
    files: [
      {
        name: "file_1",
        expired: true
      },
      {
        name: "file_2",
        expired: false
      }
    ]
  }
]

You're filtering the result array, not the sub-arrays.

This will filter the files arrays in place in the result array

 const result = [{ type: "Documents", files: [{ name: "file_1", expired: true }, { name: "file_2", expired: false }, { name: "file_3", expired: false }, { name: "file_4", expired: true }, { name: "file_5", expired: false } ] }, { type: "Images", files: [{ name: "file_1", expired: true }, { name: "file_2", expired: false } ] } ]; result.forEach(el => el.files = el.files.filter(file => file.expired === false)); console.log(result)

This will create a new array of new objects:

 const result = [{ type: "Documents", files: [{ name: "file_1", expired: true }, { name: "file_2", expired: false }, { name: "file_3", expired: false }, { name: "file_4", expired: true }, { name: "file_5", expired: false } ] }, { type: "Images", files: [{ name: "file_1", expired: true }, { name: "file_2", expired: false } ] } ]; new_result = result.map(el => ({...el, files: el.files.filter(file => file.expired === false) })) console.log(new_result)

You have files.files as array, so you have to first loop over it and then do filter, something like

result.map((files) => files.files.filter(file=> file.expired === false));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM