skip to Main Content

Basically, I am trying to list an array in the console like this, I will give an example.

config.json

{
Names: [
"Stewart",
"Bob",
"Kevin"
]
}

And then the console would print out once called in a JS file

  1. Stewart
  2. Bob
  3. Kevin

And also if I were to add more code to the array it would keep on listing numbers like that.

I haven’t tried anything yet, I am mostly new to this.

3

Answers


  1. This is how you can do this

    `const config = {
       Names: [
      "Stewart",
          "Bob",
         "Kevin"
         ]
     };
    
    for (let i = 0; i < config.Names.length; i++) {
         console.log(`${i+1}. ${config.Names[i]}`);
     }`
    
    Login or Signup to reply.
  2. run a forEach of your Names array inside your object like this

    const myObj = {
      Names: [
        "Stewart",
        "Bob",
        "Kevin"
      ]
    }
    
    const result = myObj.Names.forEach((ele, index) => { 
      let i= index+1;
      console.log(i + ' - ' + ele); 
    })

    or the alternative for loop

    const myObj = {
      Names: [
        "Stewart",
        "Bob",
        "Kevin"
      ]
    }
    
    for (let i = 0; i < myObj.Names.length; i++) {
         let index= i+1;
         console.log(index + ' - ' + myObj.Names[i]);;
     }
    Login or Signup to reply.
  3. To list the contents of an array in JS, you can use a loop.
    There are few concepts here worth looking into to understand how the example loop works:

    1. Valid json: you need quotations around the "Names" key in your config.json file
    2. The use of require() module to access the json file data
    3. The For loop: this example loops over the length of the array using the index variable as a iterator and console.log()’s value of the names array at that index
    4. What is being logged: The example has a string literal to match the numbered list example in your prompt but you can also simply log the value with console.log(names[index])
    const data = require('./config.json');
    let names = data.Names
    for (let index = 0; index < names.length; index++) {
        console.log(`${index + 1}. ${names[index]}`)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search