Skip to main content
  1. About
  2. For Teams
Asked
Viewed 7k times
2

I tried an iteration using Vue.js The result Got an error like this

[Vue warn]: Error in mounted hook: "TypeError: this.frontImages.forEach is not a function"

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 


this.frontImages.forEach(function(value, index) {

  console.log(value);

}
2
  • .forEach() will only work with arrays. It will not work for JSON objects.
    Ahmad
    –  Ahmad
    2018-12-06 09:29:06 +00:00
    Commented Dec 6, 2018 at 9:29
  • How can we iterate this object
    Muhammad ali
    –  Muhammad ali
    2018-12-06 09:31:02 +00:00
    Commented Dec 6, 2018 at 9:31

2 Answers 2

3

.forEach() will only work for arrays.

If you need to iterate through the properties of a JSON object, then here is one way of doing that:

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 

printKeysAndValues(this.frontImages);

function printKeysAndValues(anyObject) {
    Object.keys(anyObject).forEach( key => {

        // in-case properties are nested objects
        let value = JSON.stringify(anyObject[key]);  

        
        // let value = anyObject[key];   // for primitive nested properties


        console.log(`${key} = ${value}`);
    });
}

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

Comments

-1

For array:

this.frontImages = [{frontA:{name:'frontAName'},frontB:{name:'frontBName'}}]; 

this.frontImages.forEach(function(value, index) {

  console.log(value);

})

For only object iteration

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 

Object.values(this.frontImages).forEach(value => {

  console.log(value);

});

1 Comment

The OP wants to iterate through the JSON object, not to change JSON into an array.

Your Answer

Post as a guest

Required, but never shown

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.