I have an object with arrays inside. These arrays have objects that I want to access. My problem is that these arrays contain the next 5 days, so they change from time to time. The Object:
{2022-04-09: Array(5), 2022-04-10: Array(8), 2022-04-11: Array(8), 2022-04-12: Array(8), 2022-04-13: Array(8), …}
2022-04-09: (5) [{…}, {…}, {…}, {…}, {…}]
2022-04-10: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2022-04-11: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2022-04-12: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2022-04-13: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
2022-04-14: (3) [{…}, {…}, {…}]
So I want to select these arrays(so I can seperate the days) and after access the objects inside, and that is what I don't know how to do.
Lets say you have your object stored in dateObj, you dont really say what those object contain so I leave them empty. Also you say you have 5 objects in each array but in your example you have 5, 8 or 3 objects inside
const dateObj = {
'2022-04-09': [ {}, {}, {}, {}, {} ],
'2022-04-10': [ {}, {}, {}, {}, {} ],
'2022-04-11': [ {}, {}, {}, {}, {} ],
'2022-04-12': [ {}, {}, {}, {}, {} ],
'2022-04-13': [ {}, {}, {}, {}, {} ]
};
// then you can access each array in your dateObj with this:
console.log(dateObj['2022-04-09']);
// then access each object in array like this:
for (item of dateObj['2022-04-09']) {
console.log(item);
}
// or you can iterate over all keys (2022-04-09, 2022-04-10, 2022-04-11, ...)
for (key in dateObj) {
if (!(key in dateObj)) continue;
console.log(key, dateObj[key]);
// and access each object in array
for (item of dateObj[key]) {
console.log(item);
}
}
You can iterate through all your object and keys using this, then you can do whatever you like to do with the object inside the array. I am assuming your object as myObject .
So you can do it in this way,
const myObject = {
'2022-04-09': [{ content: "item 12" }, { content: "item 1-3" }, { content: "item 1-4" }, { content: "item 1-5" }, { content: "item 1-6" }],
'2022-04-10': [{ content: "item 2-1" }, { content: "item 2-2" }, { content: "item 2-3" }, { content: "item 2-4" }, { content: "item 2-5" }],
};
Object.keys(dateObj).forEach(key => {
// key will be each date of your object . like '2022-04-09'
myObject[key]?.forEach(date => {
// so myObject[key] will be each array of that object which you can itterate. so you may assume this as accessing like myObject['2022-04-09'] item.
console.log(date?.content);
})
})