[Vuejs]-How to use complex variable as object key in vue data mustache expression?

1👍

You need to understand fundamentally what your code is doing.

When you have an expression of the form first.second, you’re roughly requesting that your code retrieve the value named second from the object named first. Note that jss.man.name would then mean “retrieve the value called man from the object jss, and then retrieve the value called name from man“. Your object called jss does not contain anything called man, however, so this will return undefined, and undefined definitely does not contain a value named name. In fact, when you try to retrieve the value of a property from undefined, you’ll get an error, and when you get an error Vue will make it look like nothing is working at all.

What you’re really trying to do is find the value named name in the object named man, and then use this name to retrieve a value from jss. This looks like jss[man.name], which is one of the solutions you have in place. Simply omit the jss.man.name and your code should work:

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
      </script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ message }}</h1>
         <p>{{ jss }}</p>
         <table>
             <tr v-for="man in lst">
                 <th>{{ man.name }}</th>
                 <!--<td>{{jss.man.name}}]</td> commenting this out should fix it! -->
                 <td>{{jss[man.name]}}</td> <!-- this should be correct-->
             </tr>
         </table>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               message: 'My first VueJS Task',
               jss: {"n1": 999},
               lst: [
                   {"name": "n1"},
                   {"name": "n2"}
                   ]
            }
         });
      </script>
   </body>
</html>

As noted elsewhere, you also had an extra ] being rendered as well. I’ve removed that in the code snippet above.

-1👍

You did an extra ] in the end of one way data binding code. You can update the code like

<td>{{jss.man[name]}}</td>

or you can use,

<td>{{jss.man["name"]}}</td>

or,

<td>{{jss.man.name}}</td>

Leave a comment