Discord
Login
Community
DARK THEME

Objects inside arrays (JavaScript)

Hello everyone!

I started learning JavaScript and noticed that I can't output not the name not the contents of the object that is inside the array

Code:

init = function() {
var myWork =[];
let i=1;

for(i;i<=10;i++){
var lesson ={
  name: "Lesson " + i,
  status: i%2 ? "true" : "false"
};  
 myWork.push(lesson); 
}
print(myWork);
}

Console:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

If you look through the browser console, everything is fine there, maybe it's a bug?

If so, how about making it look like this:

cell number
    Item name: value,
    Item name: value,
    Item name: value
cell number
    Item name: value,
    Item name: value,
    Item name: value

Or in this form:

(cell number) {element name: value, element name: value}
(cell number) {element name: value, element name: value}

In JavaScript, you could use JSON.stringify to format a string representation of your object:

  print(JSON.stringify( myWork, null, 2 )) ;

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax

Good. Are there plans to make it friendlier, without this? As in microscript

You can write your own function to print a list of objects. The example only works for objects that do not contain other objects as members. You would get [object Object] again. Try this one with your code:

//javascript

printListOfObjects = function(objList){
  // iterate over list
  objList.forEach( (obj, index) => {
    print("index: " + index)
    // iterate over object keys
    for (key in obj) {
      // customise output here
      let value = obj[key]
      print("  " + key + ": " + value)
    }
  })
}

PaulSt, аlthough I have no idea how your code works ( But I'll fix it))) ), it looks cool 👍 I'll take advantage of it 😉

Both options look good in the console and it would be nice to add some of them.

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community