我正在尝试返回以下值以插入到SQL语句中:
('apple', 'fruit', '[email protected]'), ('carrot', 'vegetables', '[email protected]'), ('beans', 'vegetables', '[email protected]'), ('milk', 'dairy', '[email protected]'), ('cheese', 'dairy', '[email protected]')
这是我必须使用的数据:
const email = "[email protected]";
const body = {
"fruit": ["apple"],
"vegetables": ["carrot", "beans"],
"dairy": ["milk", "cheese"]
};
到目前为止,这是我尝试过的方法:
let values = '';
Object.keys(body).forEach(key => {
Object.keys(body[key]).forEach(item => {
values += `('${body[key][item]}', '${key}', '${email}'),`;
});
});
这将返回正确的值,但是最后一个结果的末尾带有逗号,当插入SQL时会导致错误。
有什么想法如何重写此函数以修剪上次迭代中的逗号吗?也许我应该尝试其他循环,例如for(),而不是forEach?
谢谢 :)
我会使用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句