'Add comma after object value in array

I am trying to get a result like the following in order to call a SQL query. It's an array of objects (each object with a key, that's going to be VALUE and a value. The value must be into single quotes with a comma at the end):

[
  { VALUE: 'A', },
  { VALUE: 'B', },
  { VALUE: 'C', },
  { VALUE: 'D', },
  { VALUE: 'E', },
  { VALUE: 'F' }
]

I've tried using a for function in which I add an object for each element in a list. This is the result I get:

Code:

    let arr = [];
    const len = reqBody.values.length;

    for (let i = 0; i < len; i++)
    {
        arr.push( { VALUE: reqBody.values[i] } )
    }

Result:

[
  { VALUE: 'A' },
  { VALUE: 'B' },
  { VALUE: 'C' },
  { VALUE: 'D' },
  { VALUE: 'E' },
  { VALUE: 'F' }
]

I've tried using a map arrow function with a join at the end of it in order to try to add the comma after each value (so for the second line of the result code would be something like: { VALUE: 'A', }) but I cant make it work since that returns an array of strings, not objects like the ones I need.

This is the code described above:

Code:

let arr = [];
const len = reqBody.values.length;

for (let i = 0; i < len; i++)
{
    arr.push(Object.values({ VALUE: reqBody.values[i] }).map(v => `{ VALUE: '${v}', }`).join(','))
}

Result:

[
  "{ VALUE: 'A', }",
  "{ VALUE: 'B', }",
  "{ VALUE: 'C', }",
  "{ VALUE: 'D', }",
  "{ VALUE: 'E', }",
  "{ VALUE: 'F', }",
]

Is there any way to cast that string in the map function to be an object?



Solution 1:[1]

You need to construct the entire thing as a concatenated string, not as an array.

let reqBody = {
  values: ['A', 'B', 'C']
};

let items = reqBody.values.map(v => `{ VALUE: '${v}', }`);
let result = '[\n  ' + items.join(',\n  ') + '\n]';
console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar