I'm trying to return the following values to insert in a SQL statement:
('apple', 'fruit', '[email protected]'), ('carrot', 'vegetables', '[email protected]'), ('beans', 'vegetables', '[email protected]'), ('milk', 'dairy', '[email protected]'), ('cheese', 'dairy', '[email protected]')
Here's the data I have to work with:
const email = "[email protected]";
const body = {
"fruit": ["apple"],
"vegetables": ["carrot", "beans"],
"dairy": ["milk", "cheese"]
};
Here's what I've tried so far:
let values = '';
Object.keys(body).forEach(key => {
Object.keys(body[key]).forEach(item => {
values += `('${body[key][item]}', '${key}', '${email}'),`;
});
});
This returns the correct values, but the last result has a comma on the end which causes the an error when inserted into the SQL.
Any ideas how to rewrite this function to trim the comma from the last iteration? Maybe I should try a different loop, like for(), instead of forEach?
Thanks :)
I'd use map/join:
const email = "[email protected]";
const body = {
"fruit": ["apple"],
"vegetables": ["carrot", "beans"],
"dairy": ["milk", "cheese"]
};
const values = Object.keys(body)
.map(key =>
body[key]
.map(item => `('${item}', '${key}', '${email}')`)
.join(', ')
)
.join(', ');
console.log(values);