Home > Enterprise >  Vue Js iterating over hashmaped object
Vue Js iterating over hashmaped object

Time:09-27

For hash map object:

messages = {
  3: {
    id: 3,
    user_id: 1,
    text: "My message"
  }, 

  345: {
    id:345,
    user_id: 2,
    text: "Hello There!"
  },
  ...
}

And in template I'm trying to add different styles if next and previous messages have different senders (user_id). Since this is not an array, I can't do:

messages[index 1] or messages[index - 1]

I would need exact ID of next and/or previous message. I could take ineffecient solution by converting messages object into array, finding index of current message ID and comparing ids of next and previous message senders. But it feels like there is better solution, specifically because vue v-for already has "index" exposed.

Is there better approach to this problem? Assuming I'm not creating additional variables that track ids (this just increases complexity).

CodePudding user response:

You can access like this, child being the child object

 <p v-for="(child, key, index) in obj" :key="index">{{child.id}},{{key}},{{index}}</p>

CodePudding user response:

Object.keys() Get an array of keys in the same order as the object iteration. The key of the previous iteration can be found in each iteration by finding the position of the key in this array. Access the previous value with the whole object and the previous key.

It is better to convert to an array. On the one hand the properties of ordinary objects are actually unordered, and the order in which objects are traversed often depends on the implementation of specific traversal methods by different browser JS engines. It is then easy for the user's browser to vary and thus not match expectations(though you may not have a problem with this if the key in your object is type Number). On the other hand, in this sequential display scenario, arrays are more semantic than normal objects and are actually more elegant.

If your concern is about performance, the front-end rarely needs to think about it that much.

So convert to an array maybe the truly better one.

------Edit------

Asking the back-end engineers to return an array directly may be better than 'better'.

  • Related