从嵌套forEach循环的最后一个结果中删除逗号

时间:2019-05-09 02:11:32

标签: javascript arrays foreach javascript-objects nested-loops

我试图返回以下值以插入到SQL语句中:

('apple', 'fruit', 'john@gmail.com'), ('carrot', 'vegetables', 'john@gmail.com'), ('beans', 'vegetables', 'john@gmail.com'), ('milk', 'dairy', 'john@gmail.com'), ('cheese', 'dairy', 'john@gmail.com')

这是我必须处理的数据:

const email = "john@gmail.com";
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?

谢谢:)

4 个答案:

答案 0 :(得分:2)

您可以使用slice()函数删除字符串的最后一个字符。

const email = "john@gmail.com";
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}'),`;
  });
});
values = values.slice(0,-1)

console.log(values)

更好的方法是首先flatMap()获取平面字符串,然后使用join()

const email = "john@gmail.com";
const body = {
        "fruit": ["apple"],
        "vegetables": ["carrot", "beans"],
        "dairy": ["milk", "cheese"]
}; 
let values = Object.entries(body)
                      .flatMap(([k,v]) => v.map(a => `('${v}', '${k}', '${email}')`))
                      .join(',')
console.log(values)

答案 1 :(得分:1)

我会使用map / join:

const email = "john@gmail.com";
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);

答案 2 :(得分:1)

这是在body对象的Array.reduce()上使用Object.entries()的另一种方法:

const email = "john@gmail.com";
const body = {
  "fruit": ["apple"],
  "vegetables": ["carrot", "beans"],
  "dairy": ["milk", "cheese"]
};

let res = Object.entries(body).reduce((acc, [k, v], i, arr1) =>
{
    v.forEach((e, j, arr2) =>
    {
        acc += `('${e}', '${k}', '${email}')`;
        acc += (i === arr1.length - 1 && j === arr2.length - 1) ? "" : ", ";
    });

    return acc;
}, "");

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 3 :(得分:0)

您可以更改代码,以便仅在需要时才添加逗号     让值='';

let separator = '';
Object.keys(body).forEach(key => {
  Object.keys(body[key]).forEach(item => {
    values += `('${body[key][item]}', '${key}', '${email}')` + separator;
    separator = ',';
  });
});
相关问题