I have an object that looks like:
{
"id": 1,
"name": "Customer",
"parks": {
"1": "Park a",
"23": "Park b",
"7": "Park c",
"83": "Park d"
},
"users": {
"11": "[email protected]"
}
}
The value on the left side in parks
and users
is not an index, but the actual id
of the Park. How can I access this value in Javascript?
Currently I use Vue.Js, so I'm binding the value like this to a component:
<park-component v-for="park in customer.parks"
v-bind:prop="park"
v-bind:key="park.id">
</park-component>
This however, only binds the park value on the right side, i.e the name "park a". I need to be able to access the left side as well. If not possible through Vue in the html, can it be done in the script? i.e if I have:
"23": "park b"
How can I get 23
?
You can iterate through objects using the v-for
directive and get the key.
<ul>
<li v-for="(value, key) in object">{{ key }}: {{ value }} </li>
</ul>
new Vue({
template: `
<ul>
<li v-for="(value, key) in object">{{ key }}: {{ value }} </li>
</ul>
`,
data: () => {
return {
object: {
key1: 'value1',
key2: 'value2',
key3: 'value3',
},
};
},
}).$mount('#root');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>
you first get the keys with: Object.keys
and then loop it :)
I've included example how to access the values!
var test = {
"id": 1,
"name": "Customer",
"parks": {
"1": "Park a",
"23": "Park b",
"7": "Park c",
"83": "Park d"
},
"users": {
"11": "[email protected]"
}
};
var keys = Object.keys( test.parks );
for (var i = 0; i < keys.length; i++){
console.log( test.parks[ keys[ i ] ] )
}
There is no element as id
in park
, use index
like this
<park-component v-for="(park,index) in customer.parks"
v-bind:prop="park"
v-bind:key="index">
</park-component>
var parkComponent = Vue.extend({
template: "<div>Key : {{park_key}}, Prop : {{prop}}</div>",
props: ['prop','park_key']
});
var app = new Vue({
el: "#vue-instance",
data: {
customer:{
"id": 1,
"name": "Customer",
"parks": {
"1": "Park a",
"23": "Park b",
"7": "Park c",
"83": "Park d"
},
"users": {
"11": "[email protected]"
}
}
},
mounted() {
},
components: {
parkComponent,
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
<park-component v-for="(park,index) in customer.parks"
v-bind:prop="park"
v-bind:park_key="index">
</park-component>
</div>
Note : key
will not work here v-bind:key
as key
is reserved
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With