skip to Main Content

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.

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?

2

Answers


  1. 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]);
    }
    
    Login or Signup to reply.
  2. Change your for loop to a foreach loop

    Object.keys(this.data).forEach(key => {
       return this.data[key]; // or whatever
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search