2๐
โ
Try this code
var json = {
"Home work": [
{
"id": 5,
"student_id": 2,
"activity_id": 3,
"checked": 1,
"checked_at": "2023-02-07 06:03:06",
"completed": 1,
"created_at": "2023-02-06T12:31:22.000000Z",
"updated_at": "2023-02-07T06:03:11.000000Z",
"activity_category_name": "Home work"
},
{
"id": 2,
"student_id": 2,
"activity_id": 2,
"checked": 1,
"checked_at": "2023-02-07 06:03:38",
"completed": 0,
"created_at": "2023-02-06T10:44:31.000000Z",
"updated_at": "2023-02-07T06:03:38.000000Z",
"activity_category_name": "Home work"
}
],
"Daily activity": [
{
"id": 1,
"student_id": 2,
"activity_id": 1,
"checked": 1,
"checked_at": "2023-02-05 11:18:56",
"completed": 1,
"created_at": "2023-02-05T10:40:25.000000Z",
"updated_at": "2023-02-05T11:18:56.000000Z",
"activity_category_name": "Daily activity"
}
]
};
var keys = Object.keys(json);
for (const key of keys) {
console.log(key);
var result = keys.indexOf(key);
console.log(result);
}
๐คm7s
2๐
Since it is an Object, We cannot access its key "Home Work" as index 0 but you can try Object.keys(yourObject) to access all of its keys.
๐คDevender Kumar
1๐
You can get the index numbers of keys of an object just by using the Object.keys()
method, which returns a list of all the keys of the object. Then, you use forEach
method to iterate over the list of keys and get the index of each key.
Example:
var yourObject = {
"Home work": [
{
"id": 5,
"student_id": 2,
"activity_id": 3,
"checked": 1,
"checked_at": "2023-02-07 06:03:06",
"completed": 1,
"created_at": "2023-02-06T12:31:22.000000Z",
"updated_at": "2023-02-07T06:03:11.000000Z",
"activity_category_name": "Home work"
},
{
"id": 2,
"student_id": 2,
"activity_id": 2,
"checked": 1,
"checked_at": "2023-02-07 06:03:38",
"completed": 0,
"created_at": "2023-02-06T10:44:31.000000Z",
"updated_at": "2023-02-07T06:03:38.000000Z",
"activity_category_name": "Home work"
}
],
"Daily activity": [
{
"id": 1,
"student_id": 2,
"activity_id": 1,
"checked": 1,
"checked_at": "2023-02-05 11:18:56",
"completed": 1,
"created_at": "2023-02-05T10:40:25.000000Z",
"updated_at": "2023-02-05T11:18:56.000000Z",
"activity_category_name": "Daily activity"
}
]}
To get both keys and their index, use:
Object.keys(yourObject ).forEach((key, index) => {
console.log(`Key:: ${key}, index:: ${index}`)
})
If you want to get only the indexes of the keys, use:
Object.keys(yourObject ).forEach((key, index) => {
console.log(index)
})
๐คHassan Ali
Source:stackexchange.com