Is there a way to get values from the object by chaining variables? I don’t know how to define this idea, but with examples it would be clear.
const ID_COUNT = 4;
const data = {
"id_1": 1,
"id_2": 2,
"id_3": 3,
"id_4": 4,
}
console.log(data.id_1)
console.log(data.id_2)
console.log(data.id_3)
console.log(data.id_4)
for(let i=0; i < ID_COUNT; i++){
let obj_id = `id_${i}`;
console.log(data.obj_id)
}
OUPUT
1
2
3
4
undefined
undefined
undefined
undefined
As you can see, if I just print exactly value what I want in console log then result is as expected, but I want loop through some count of objects in data and print out object values. How can I do that? If key value changes just number but starts always the same id_ and number
>Solution :
Use bracket notation for dynamic access.
console.log(data[obj_id])