0

How can I get the length of a json object in vue?

I use axios to post a keyword to my PHP script which returns JSON like this:

1: {image: "cms/images/producten/universele-folie/thumbnail/orajet_folie_wit.jpg",…}
2: {image: "cms/images/producten/wrap-cast/thumbnail/wrap.jpg", title: "Wrap folie",…}
3: {image: "cms/images/producten/transparante-folie/thumbnail/orajet_folie_transparant.jpg",…}
4: {image: "cms/images/producten/zandstraalfolie/thumbnail/materiaal-folie-zandstraalfolie.png",…}
5: {image: "cms/images/producten/vloerfolie/afbeeldingen/544_587cdea0a62b4429_2.jpg",…}
6: {image: "cms/images/producten/easy-folie/afbeeldingen/easy_dot.jpg",…}

I want to limit this object so that when looping it, it stops at 6. But I have no clue how to get the length of this object, how can I see that there are in above example 6 results?

I tried .length but this does not work on objects. I've tried .keys like in below example:

let app = Vue.createApp({
    data: function(){
        return{
            // Object to fill with JSON response
            responsedata:{},
            showResultDiv: false
        }
    },
    methods:{
        // Function to show loading dots until json returned
        loadDiv(condition, content){
            this.showResultDiv = condition
        },
        async fetchResults(){
            await axios.post('includes/searchproducts_json.php', {
                // Post data, add value of input to searchterm
                searchterm: this.$refs.searchterm.value
            })
            .then((response)=>{
                this.responsedata = response.data
                console.log(this.responsedata.keys)
            })
            .catch((error)=>{
                console.log(error)
            })
        }
    },
    computed: {

    }
})

app.mount('#v_search');

But this just logs undefined. How can I limit this object? Preferably create 1 object to loop with just 6 results and a data object that contains the number of all results.

1

1 Answer 1

2

You can use Method 1: Object.keys(yourObject)

Object.keys(this.responsedata).length

However, this method has memory overhead and would be slower than Method 2

Method 2: for-loop

let objectSize = 0;
for(let k in this.responsedata) {
  objectSize++
}
// objectSize here holds the size of your object
return objectSize

This methods would be slightly faster because of better memory usage.

As noted by @Simon K, you can check more here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.