Reputation: 12847
I have an object that looks like this, and I can push data using below method. Also I initialize the types
data.
myObj = {
1: ["a", "b", "c"],
2: ["c", "d", "e"],
}
data: {
types: {}
},
methods: {
pushValue(key, value) {
var obj = this.types
if (obj.hasOwnProperty(key)) {
var idx = $.inArray(value, obj[key]);
if (idx == -1) {
obj[key].push([value]);
}
} else {
this.$set(obj, key, [value]);
}
},
}
It works fine.
However, now I want my object to look like this:
myObj = {
1: {
"a": [
[],[]
],
"b": [
[],[]
],
}
}
How can I modify my append function to append the elements like this?
Upvotes: 0
Views: 193
Reputation: 4438
I'm just answering this according my assumption of what @senty is trying to do:
pushValue is a method that takes numbers as key
s and characters as value
s and save them into this.types
, and whenever pushValue
is called, this.types
is gonna have a property key
storing an object with value
as its key, which stores an array containing an empty array. If That array (the one that contains arrays) already exists, another empty is gonna appended to that array. And eventually this.types
will look like myObj
Hence, pushValue
should look like this:
const app = new Vue({
el: '#app',
data: {
types: {}
},
methods: {
pushValue(key, value) {
if (this.types.hasOwnProperty(key)) {
if (this.types[key].hasOwnProperty(value)) {
const orgValue = this.types[key][value];
orgValue.push([]);
this.$set(this.types[key], value, orgValue);
} else {
this.$set(this.types[key], value, [[]]);
}
} else {
this.$set(this.types, key, {
[value]: [ [] ]
});
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div>
<p>pushValue(key, value)</p>
<button v-on:click="pushValue(1, 'a')">(1, 'a')</button>
<button v-on:click="pushValue(1, 'b')">(1, 'b')</button>
<button v-on:click="pushValue(1, 'c')">(1, 'c')</button>
<button v-on:click="pushValue(2, 'a')">(2, 'a')</button>
<button v-on:click="pushValue(2, 'b')">(2, 'b')</button>
<button v-on:click="pushValue(2, 'c')">(2, 'c')</button>
</div>
<div>{{ types }}</div>
</div>
Upvotes: 2