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

Remove comma from last result in nested forEach loop

我正在尝试 return 将以下值插入到 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}'),`;
  });
});

这个 return 是正确的值,但最后一个结果的末尾有一个逗号,这会导致插入 SQL 时出错。

关于如何将此函数重写为 trim 上次迭代的逗号有什么想法吗?也许我应该尝试不同的循环,比如 for(),而不是 forEach?

谢谢:)

您可以使用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)

我会使用 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);

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

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

这是另一种使用 body 对象的 Array.reduce() over the 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;}