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)
empty array and I'm not sure what I'm doing wrong.
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
}
]
}
]
CodePudding user response:
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)
CodePudding user response:
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));