Home > front end >  How to iterate the array keys in vuejs?
How to iterate the array keys in vuejs?

Time:01-13

My code :

<div >
  <h3>Archives :</h3>
  <div  v-for="list in archives" :key="list.length">
    <p>{{  }}</p>
  </div>
</div>

Data from the server :

{
  archives: {
    2023: {
      1: ["3", "ABCD"]
    }
  }
}

Expected output :

archives: {
  2023: {
    1: ["3", "ABCD"]
  }
}

2023: {
  1: ["3", "ABCD"]
}

1: ["3", "ABCD"]

0: "3"

1: "ABCD"

I want to display the key on my screen. Here is the key I want to display (2023 and 1) that I received as key. I don't know how to iterate the key. And also I want to display the value (ABCD, 3).

CodePudding user response:

As per my understanding, You have an archives object and you want to print their keys along with the values in a recursive way with the help of v-for. I am assuming the expected output mentioned below.

Input object :

{
  archives: {
    2023: {
      1: ["3", "ABCD"]
    }
  }
}

Expected output :

2023: {
  1: ["3", "ABCD"]
}

1: ["3", "ABCD"]

0: "3"

1: "ABCD"

If my understanding is correct, Here is the live demo :

new Vue({
  el: '#app',
  data: {
    archives: {
      2023: {
        1: ["3", "ABCD"]
      }
    },
    keysArr: []
  },
  mounted() {
    this.iterateObject(this.archives);
  },
  methods: {
    iterateObject(obj) {
      Object.keys(obj).forEach(key => {
        if (typeof obj[key] === 'object') {
          this.keysArr.push({
            [key]: obj[key]
          });
            this.iterateObject(obj[key])
        } else {
            this.keysArr.push({
            [key]: obj[key]
          });
        }
      })    
    }
  },
  computed: {
    Objectkeys() {
        return this.keysArr
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>Archives :</h3>
  <div  v-for="(item, index) in Objectkeys" :key="index">
    <pre>{{ item }}</pre>
  </div>
</div>

CodePudding user response:

You can use Object.keys method which will return the keys of an object as an array. In your case you can recursively call it inside of a function to iterate over nested object

const getKeys = (obj) => {
    Object.keys(obj).forEach((key) => {
        //
        if (type obj[key] == "object") {
            getKeys(obj[keys])
        }
    })
}
  • Related