0

I would like to achieve this JSON structure:

{
  "people": [
    {
      "name": "Peter",
      "surname": "Green"
    },
    {
      "name": "Jessica",
      "surname": "Morgan"
    },
    ...
}

I am trying to do it like this:

People({}).sort('-createdAt').exec(function(err, people) {
        if(err) throw err;
        console.log(people);

        let data = {}
        data['people'] = [];
        data.push(people);
        res.json(data);
    });

When I look at the generated JSON structure, it is in this format:

{
    "people": [
        [
            {
               "name": "Peter",
               "surname": "Green"
            },
            ...

In the JSON, there are two arrays in the people section. How do I get rid one of the array from there?

Thank you

1 Answer 1

2

I assume you're reading from a database, and it looks like it's returning an array of people.

Try not pushing it into a new array?

People({}).sort('-createdAt').exec(function(err, people) {
        if(err) throw err;
        console.log(people);

        let data = {
            people: people
        };
        res.json(data);
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Or simply use res.json({ people });
Correct (gave you an upvote). I am always a little careful about using more advanced syntax when answering a question.

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.