Home > Net >  Looping through object until param found (VueJS)
Looping through object until param found (VueJS)

Time:10-30

I have this data:

    example: {
        "jd5jasjs71kdskzaslsdfsdfsdfsdf" : {
            param1: '',
            param2: '',
            param3: '',
            param4: 'xx',
            param5: 'xx',
            advancedParams: {
                aone: '',
                atwo: '',
                athree: '',
                afour: 'blablabla'
            }
        },

I have this code which worked fine, until I figured out I'll need another set of data in the object to be implemented as form fields in later stages of the form I'm creating:

    if (this.example.hasOwnProperty(this.someKey)) {
        for (const [key, value] of Object.entries(this.example[this.someKey])) {
            this.newInputs[key] = value;
        }
    }

someKey newInputs(object) are from the Data()

What I'm trying to accomplish here is to divide fields to two new objects which will be rendered later as form fields.

Example:

newInputs: {
            param1: '',
            param2: '',
            param3: '',
            param4: 'xx',
            param5: 'xx',
}

aParams: {
                aone: '',
                atwo: '',
                athree: '',
                afour: 'blablabla'
}

I was able to do it but not 100% good, I was able to split it to two objects but "advancedParams" got into the first object as a field also(which I don't him to be)

CodePudding user response:

Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      newInputs: {},
      aParams: {},
      someKey: 'jd5jasjs71kdskzaslsdfsdfsdfsdf',
      example: {
        "jd5jasjs71kdskzaslsdfsdfsdfsdf" : {
          param1: '',
          param2: '',
          param3: '',
          param4: 'xx',
          param5: 'xx',
          advancedParams: {
              aone: '',
              atwo: '',
              athree: '',
              afour: 'blablabla'
          }
        }
      }
    }
  },
  methods: {
    splitData() {
      if (this.example.hasOwnProperty(this.someKey)){
        for (const [key, value] of Object.entries(this.example[this.someKey])){
          if(typeof value !== 'object'){
            this.newInputs[key] = value; 
          } else {
            this.aParams = value;
          }
        }
      }
    }
  },
  mounted() {
    this.splitData()
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
      <p>newInputs = {{ newInputs }}</p>
      <p>aParams = {{ aParams }}</p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related