Vue.js如何从Json属性获取键(左侧值)。

时间:2017-11-07 10:09:46

标签: javascript vue.js

我有一个看起来像的对象:

{
  "id": 1,
  "name": "Customer",
  "parks": {
    "1": "Park a",
    "23": "Park b",
    "7": "Park c",
    "83": "Park d"
  },
  "users": {
    "11": "user@customer.com"
  }
}

parksusers左侧的值不是索引,而是Park的实际id。如何在Javascript中访问此值?

目前我使用的是Vue.Js,所以我将这样的值绑定到一个组件:

<park-component v-for="park in customer.parks"
                            v-bind:prop="park"
                            v-bind:key="park.id">
</park-component>

然而,这仅限于右侧的停车价值,即名称“停放a”。我也需要能够访问左侧。如果不能通过html中的Vue实现,可以在脚本中完成吗?即如果我有:

"23": "park b"

我如何获得23

3 个答案:

答案 0 :(得分:12)

解决方案

您可以使用v-for指令迭代对象并获取密钥。

<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>

进一步阅读

答案 1 :(得分:1)

首先获取密钥:Object.keys然后循环它:)

我已经包含了如何访问这些值的示例!

&#13;
&#13;
var test = {
  "id": 1,
  "name": "Customer",
  "parks": {
    "1": "Park a",
    "23": "Park b",
    "7": "Park c",
    "83": "Park d"
  },
  "users": {
    "11": "user@customer.com"
  }
};

var keys = Object.keys( test.parks );

for (var i = 0; i < keys.length; i++){
  console.log( test.parks[ keys[ i ] ] )
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

id中没有park元素,请像这样使用index

<park-component v-for="(park,index) in customer.parks"
                        v-bind:prop="park"
                        v-bind:key="index">
</park-component>

&#13;
&#13;
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": "user@customer.com"
        }
      }
    },
    mounted() {
    },
    components: {
        parkComponent,
    },
})
&#13;
<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>
&#13;
&#13;
&#13;

注意key无效v-bind:keykey已保留