I have an array like this:
const data = [
{
id: '3499934913',
user_data: {
user_data_stays: [
{
value: '30.0',
date: '2021-10-01T12:55:00.000Z',
},
{
value: '30.0',
date: '2021-11-01T12:55:00.000Z',
},
{
value: '30.0',
date: '2021-13-01T12:55:00.000Z',
}
],
}
},
{
id: '43534535',
user_data: {
user_data_stays: [
{
value: '30.0',
date: '2021-11-01T12:55:00.000Z',
},
{
value: '30.0',
date: '2021-12-01T12:55:00.000Z',
},
{
value: '30.0',
date: '2021-13-01T12:55:00.000Z',
}
],
}
},
]
How can I keep the structure of the whole array but filter in user_data_stays only those objects which date is equal to 2021-10-01T12:55:00.000Z?
I tried using filter and some but I am not able to get to the nested element inside. I think the problem is the amount of nesting, and I can't deal with that. I would appreciate your help.
You could use forEach on the outer array and run filter method on inner array with the help of de-structuring, the object reference will update the outer object in-place.
const data = [
{
id: "3499934913",
user_data: {
user_data_stays: [
{ value: "30.0", date: "2021-10-01T12:55:00.000Z" },
{ value: "30.0", date: "2021-11-01T12:55:00.000Z" },
{ value: "30.0", date: "2021-13-01T12:55:00.000Z" },
],
},
},
{
id: "43534535",
user_data: {
user_data_stays: [
{ value: "30.0", date: "2021-11-01T12:55:00.000Z" },
{ value: "30.0", date: "2021-12-01T12:55:00.000Z" },
{ value: "30.0", date: "2021-13-01T12:55:00.000Z" },
],
},
},
];
data.forEach(({ user_data }) => {
user_data.user_data_stays = user_data.user_data_stays
.filter(({ date }) => date === '2021-10-01T12:55:00.000Z');
});
console.log(data);