[Vuejs]-Bind Vue to associative array

1👍

I think I understand your question now with the comments you added.

This section of the documentation can help you. You can declare your data object like this:

// data must be a function
data() {
  return {
    items: {
      i: {}
    }
  }
}

And later add items like this:

vm.$set(this.items.i, 'one', true);
vm.$set(this.items.i, 'two', false);

// and later retrieve
let key = 'one';
let a = vm.items.i[key];

Remember that since data must be a function in components, you can potentially avoid the $set() calls and setup your data object at "construction time" in the data() function.

Original answer

Not to sound condescending, but I suggest you read up some more on Javascript basics. An associative array as you call it is simply an object in Javascript. This doesn’t have much to do with vue.js.

Here’s how to do it:

data: {
   items: {
      i: {
         one: true,
         two: false,
      }
   }
}
👤bernie

2👍

There’s nothing specific to Vue here, it’s just JavaScript. Simple objects can be used as associative arrays. So simply this:

data: {
   items: {
      i: {
         one: true,
         two: false
      }
   }
}

While you can access the value as let a = vm.items.i['one']; the use of square brackets is usually reserved for accessing dynamic values or those containing special characters. It would be more normal to write let a = vm.items.i.one;.

0👍

Associative arrays in JavaScript confused me as well until I realized that JavaScript does not support associative arrays like other languages do. Here is a decent page on the subject at w3schools.com.

From that page: “Many programming languages support arrays with named indexes.

“Arrays with named indexes are called associative arrays (or hashes).

“JavaScript does not support arrays with named indexes.

“In JavaScript, arrays always use numbered indexes.”

The page also includes this notice: “WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.”

Leave a comment