0

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?

2
  • 4
    Why would you need this? If the database column is supposed to contain JSON, the extra comma is not valid there. Commented May 18, 2022 at 20:37
  • 3
    This sounds like a textbook xy problem Commented May 18, 2022 at 20:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.