user2932090
user2932090

Reputation: 331

NodeJS - how to create a JSON file with an array inside in a specified format?

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

Upvotes: 0

Views: 54

Answers (1)

Jim B.
Jim B.

Reputation: 4694

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

Upvotes: 2

Related Questions