0

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:

{
    "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.

  • Because `data` is an array, you can still refer to each of the elements numerically. Assuming json is the variable name for my example, this `json.data[0]` would get the first element in the array. – imvain2 Aug 22 '23 at 17:34
  • @imvain2 thank you for the reply, yes I am currently doing that however for my specific use case I'm looking to get that desired results. Any idea how? – Marwan Ansari Aug 22 '23 at 17:40
  • 1
    Your desired result is invalid because arrays don't have string keys. You either need to use an object or just use the array indices like @imvain2 suggested. – mykaf Aug 22 '23 at 17:44

1 Answers1

1

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)
imvain2
  • 15,480
  • 1
  • 16
  • 21