0

The following is a two dimensional array, I just need to print it, but when I loop inside of it I get [object object] or undefined

const myarra = function(){
    return [
        [
          { "dayOfMonth" : 1, "dayOfWeek" : "Fri", "event" : "" },
          { "dayOfMonth" : 2, "dayOfWeek" : "Sat", "event" : "" }
        ]
    ];
};
Matze
  • 5,100
  • 6
  • 46
  • 69
  • Can you show the relevant code? – Teemu Sep 20 '17 at 19:05
  • [This post](https://stackoverflow.com/questions/10021847/for-loop-in-multidimensional-javascript-array) may help you – juanlumn Sep 20 '17 at 19:05
  • `console.log(output);` return gives you variables for assignment – Matthew Ciaramitaro Sep 20 '17 at 19:06
  • see [here](https://stackoverflow.com/questions/44439410/why-is-return-used-instead-of-console-log) and [here](https://stackoverflow.com/questions/42126844/whats-the-difference-between-console-log-and-return-in-javascript) for explanations on `console.log()` and `return` – Matthew Ciaramitaro Sep 20 '17 at 19:09

3 Answers3

1

This way you can trace each elements in your array.

Also you can use JSON.stringify(arrayVariable) method if you just want to print that array using console.log(JSON.stringify(arrayVariable)) this code.

 function myfunction(){
   var array=[[{"dayOfMonth":1,"dayOfWeek":"Fri","event":""},
         {"dayOfMonth":2,"dayOfWeek":"Sat","event":""}]];
    
    for(var i=0;i<array.length;i++){
     for(var j=0;j<array[i].length;j++){
    console.log(array[i][j]);
     }
    }
 };
  
  myfunction();
Jino Shaji
  • 1,097
  • 14
  • 27
  • can you tell me how to print it with JSON.stringify(arrayVariable)? –  Sep 20 '17 at 19:16
  • `JSON.stringify()` will Convert a JavaScript value into a string and it will output that string in console using `console.log(JSON.stringify(arrrayvariable))`. For more info about JSON.stringify() refer the [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). – Jino Shaji Sep 20 '17 at 19:22
  • Is this is your expected answer? – Jino Shaji Sep 20 '17 at 19:24
0

You can use JSON.stringify()

const myarra = function(){
  return [[{"dayOfMonth":1,"dayOfWeek":"Fri","event":""},
         {"dayOfMonth":2,"dayOfWeek":"Sat","event":""}]];
  };

JSON.stringify(myarra())
squiroid
  • 13,809
  • 6
  • 47
  • 67
-1

because it first creates this array and then writes

"[[{"dayOfMonth":1,"dayOfWeek":"Fri","event":""},
     {"dayOfMonth":2,"dayOfWeek":"Sat","event":""}]];"
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Keji
  • 1