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

Access index 0 of array that has numbered keys starting at unknown values

I have an object that is generated in php that looks something like:

Object { 1: {…}, 2: {…}, 3: {…} etc..}

It is sent from the backend to the vue.js frontend, where it’s iterated through and put into some charts.

I have a filter set up that filters based on content within the objects, but I’m having an issue with the keys that the objects are sent with. As soon as I filter, any loops that I have that require using the indices of the objects to access them break.

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

For example, say I have a loop like:

for (let i = 0; i < Object.keys(this.data).length; i++) {
   return this.data[i]; //or whatever
}

Because the backend sends the data with preexisting numbered keys, if the filter results in a set of objects that are no longer numbered 0, 1, 2, 3, 4 etc but are instead something like 3,5,6,8 then the loops will break because it will look for index [0] and not find it.

What’s the best way to handle this in javascript? Can I strip the object of the keys? Or ignore the keys and still look for this.data[0] in some way that ignores the numbered keys?

>Solution :

The solution is in your question, you can simply use Object.keys() to iterate over the keys, regardless of their type:

Object.keys(this.data).forEach(key => {
   console.log(this.data[key]);
});

If you want to keep using a similar syntax, use the following instead:

for (const key in this.data) {
    console.log(this.data[key]);
}
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