0

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>`)
})

1 Answer 1

1

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
    );
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer is there a way to display it in the app.get ?
It depends on how you are invoking sortGroup method.
I have modified the my answer to suit your needs.

Your Answer

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.