Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access to object values with chaining variables?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use bracket notation for dynamic access.

console.log(data[obj_id])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading