LisAnn
LisAnn

Reputation: 23

Populate an array with a for loop and display it

I didn't figure out how to populate an array and display it as soon as i target the route, i'm starting with nodeJs.

At the moment i'm able to console Log a list of object, i want to populate an array and display it when i do localhost:3000/

sortGroup=(group)=> {
    for (const entry of group.entries) {
        console.log(`Entry: ${field(entry, 'Name')}: UserName: ${field(entry, 'Surname')} || Age:  ${field(entry, 'Age')} || Age: ${field(entry,'Address')}`)             
    }
    for (const subGroup of group.groups) {
        sortGroup(subGroup)
    }
}

app.get('/',async (req, res) => {
    res.send(`<h1> I want to display the table</h1>`)
})

Upvotes: 0

Views: 184

Answers (1)

Phanindra
Phanindra

Reputation: 329

You can use push method to add new elements to the array

sortGroup = (group, result = [])=> {
    for (const entry of group.entries) {
        // Notice that I'm using push method
        result.push(`Entry: ${field(entry, 'Name')}: UserName: ${field(entry, 'Surname')} || Password:  ${field(entry, 'Age')} || URL: ${field(entry,'Address')}`)          
    }
    for (const subGroup of group.groups) {
        sortGroup(subGroup, result)
    }
    return result
}

app.get('/',async (req, res) => {
    // call sortGroup method
    const group = []; // You need to populate group somehow here
    const result = [];
    // As you are calling the below function recursively, its good to pass the array
    sortGroup(group, result)
    return res.json(
      // you can add any object here
      result
    );
})

Upvotes: 1

Related Questions