0

Looking to create a JSON response body with JavaScript/Postman as a pre-request script with some dynamic variables. The issue I'm having is dynamically generating arrays inside the array. The data I'm receving is a CSV file so the value is like so Value1|Value2 and I need to separate the values from the pipe separator and pushing them into their own category array

Using the CSV value from the above example the output should be like this:

{
"id": 1,
"store": 1,
"title": custom_title,
"url": custom_url,
"content": content,
"categories":[
    {
       "id":1,
       "name":"Value1",
       "type":"Type"
     },
     {
       "id":1,
       "name":"Value2",
       "type":"Type"
     },
    //add more if needed dynamically
]
}

I tried something like this

var catNum = "Blog|Healthy".split('|');
catNum.forEach((value, name) => bodyRequest.categories.push({ 
    "id": 1,
    "type": "Category",
    "name": value.toLowerCase(),
    "blog_category_path": value
}));

Trying to push the above into the categories array "categories":[]

Jose Gomez
  • 43
  • 10
  • And the actual problem is? -> [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) + [mcve] – Andreas Oct 22 '21 at 14:01
  • 1
    The second argument of the `.forEach()` callback is not a "name" – Andreas Oct 22 '21 at 14:02
  • Use `Array.map()` instead of `Array.forEach()`. And if you want to use `forEach`, use `forEach(([ value, name ]) =>` so that the value and name actually get spread correctly after splitting. Else use something like `value[ 0 ]` and `value[ 1 ]` to correctly extract the name and value. – Shilly Oct 22 '21 at 14:32

1 Answers1

0
var catNum = "Blog|Healthy".split('|');

returns an array strings to catNum.

Do this rather

catNum.forEach(value => bodyRequest.categories.push({ 
    "id": 1,
    "type": "Category",
    "name": value.toLowerCase(),
    "blog_category_path": value
}));
Isah Ohieku
  • 1
  • 1
  • 2