Search code examples
vue.jsv-forv-model

How to change key name of JSON object via vue js


I have some problems with changing key names "User1" and "User2" of the JSON object with vue.

myJSON = {"User1": {"damage": "10000"}, "User2": {"damage": "10000"}}
users = ["User1","User2","User3","User4"]

This is code of loop, and some comments. Actually problem is I can't use "key" in v-model...

<div class="mb-3" v-for="(item, key, index) in myJSON">
 <el-select v-model="key" filterable placeholder="Select"> // This is doesn't work - it's my problem =)
  <el-option
   v-for="cl in users"
   :key="cl"
   :label="cl"
   :value="cl">
  </el-option>
 </el-select>
 <el-input-number v-model="item.damage"></el-input-number> // It's okey, damage is changing.
</div>

I have already tried to change v-model on:

v-model="item.key" // JSON after this
myJSON = {"User1": {"damage": "10000", "key": "User3"}, "User2": {"damage": "10000", "key": "User4"}}

v-model="myJSON[key]" // Have error
TypeError: Cannot read property 'myJSON' of undefined

v-model="myJSON[key]" // Same
TypeError: Cannot read property 'myJSON' of undefined

After select user in <el-select> i need smth like this:

{"User2": {"damage": "10000"}, "User3": {"damage": "10000"}}

Or

{"User3333": {"damage": "10000"}, "User312321": {"damage": "10000"}}

But I'm on the not right way, please help.


Solution

  • Not sure if you can directly change an obj's key with v-model, but there is a workaround.

    <div id="app">
     <ol>
      <li v-for="(item, index) in myJSON_format2">
       {{item}}
       <input v-model="item.damage"/>
       <input v-model="item.key"/>
      </li>
     </ol>
    </div>
    
    new Vue({
     el: "#app",
     data: {
      myJSON: {"User1": {"damage": "10000"}, "User2": {"damage": "10000"}},
      myJSON_format2: []
     },
     methods: {
      change_myJSON_toFormat2 () {
        for (let i in this.myJSON) {
         this.myJSON_format2.push({ damage: this.myJSON[i].damage, key: i })
        }
      }
     },
     created () {
      this.change_myJSON_toFormat2()
     }
    })
    

    Pls check it out here: https://jsfiddle.net/shivampesitbng/dync94kt/24/

    • Workaround:
      1. Changed the ds of myjson to array of obj
      2. looped the arr with v-for in vue-template
      3. changed the "user" key as you were changing "damage" key.