I got an array with objects
"times": [{
"id" : "id",
"name" : "place",
"location" : "place",
"hours" : [
{"day": "Sunday", "day_id": 0,
"tags": "" },
{"day": "Monday", "day_id": 1,
"tags": "" },
{"day": "Tuesday", "day_id": 2,
"tags": "" },
{"day": "Wednesday", "day_id": 3,
"tags": "" },
{"day": "Thursday", "day_id": 4,
"tags": "" },
{"day": "Friday", "day_id": 5,
"tags": "" },
{"day": "Saturday", "day_id": 6,
"tags": "" }
]
}
]
I am trying to filter into the Hours array within the object.
I am trying to find the objects that contains a specific day_id within the hours array.
I tried
let f1 = times.filter((item: { id: string; hours: { day_id : number;};}) => item.hours.day_id == 0 );
That did not work. What am I doing wrong here ?
3
Answers
If you wrap the above code in a JSON object like this:
You can write a function to filter the hours sub-array by day_id as such:
Note that this only really extracts an entry from the hours sub-array and leaves everything else untouched. If you want to filter objects in the times array, you can use the following:
I can’t understand your question. But I think that you are trying to filter the times array which you will get from a json, so let’s put it in a variable
Now we have it in a variable, but the times is an array and you want to filter the hours array inside each item of that array, so this will be a nested filter:
The issue with your current approach is that hours is an array, so you need to iterate over each item in the hours array to check the day_id. Additionally, since hours is an array of objects, you cannot directly access day_id on item.hours. You need to iterate over each hour object and then check its day_id.
});