Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pushing to JSON array with name of node

I have the below code to push new objects to an array and display the JSON:

let paragraph_json = [];

for (let paragraph = 1; paragraph <= 3; paragraph++) {
  paragraph_json.push({
    text: `this is paragraph ${paragraph}`,
  });
}

res.json({
  data: paragraph_json,
});

and I get the following JSON:

{
    "data": [
      {
        "text": "this is paragraph 1"
      }, 
      {
        "text": "this is paragraph 2"
      }, 
      {
        "text": "this is paragraph 3"
      }
    ]
}

However I need something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "data": [
      "1": {
        "text": "this is paragraph 1"
      }, 
      "2": {
        "text": "this is paragraph 2"
      }, 
      "3": {
        "text": "this is paragraph 3"
      }
    ]
}

Where the paragraph number ("1", "2", "3"…) is appended before the node (opening curly braces) of that paragraph.

Any idea how can it be done from within the loop? Sorry, I’m a beginner and any code that I try basically gives me syntax error.

Slight changes in the array/json type would be fine.

>Solution :

Since arrays can’t have string keys, you will need to use objects.

For my answer, I added data as a child object of paragraph_json and used the paragraph variable as the key and set the text value accordingly.

let paragraph_json = {
  "data": {}
};
for (let paragraph = 1; paragraph <= 3; paragraph++) {
  paragraph_json["data"][paragraph] = {text: `this is paragraph ${paragraph}`};
}

console.log(paragraph_json)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading