我有一个 MySQL 表,如下所示:
id product_id option_type
-------------------------------
14 6 2
15 6 1
16 6 1
17 6 2
18 6 2
在 Sequelize ORM
上面的 sql 表的帮助下应用 sql 查询呈现下面的对象数组和 option_type
键我需要生成基于 option_type
值的集合组合:var records = [
{ id: 14, value: "M", product_id: 6, option_type: 2 },
{ id: 15, value: "White", product_id: 6, option_type: 1 },
{ id: 16, value: "Black", product_id: 6, option_type: 1 },
{ id: 17, value: "S", product_id: 6, option_type: 2 },
{ id: 18, value: "L", product_id: 6, option_type: 2 }]
我已经使用 Array.prototype.filter()
方法创建了组合。const option_type_1 = records.filter((el) => { return el.option_type == 1 });
const option_type_2 = records.filter((el) => { return el.option_type == 2 });
for(const opt1 of option_type_1) {
for(const opt2 of option_type_2) {
const options = {
"opt_one_id": opt1.id,
"opt_two_id": opt2.id,
};
optionList.push(options)
}
}
并得到如下回应......{
"data": [
{ "opt_one_id": 15, "opt_one_value": White, "opt_two_id": 14, "opt_two_value": M },
{ "opt_one_id": 15, "opt_one_value": White, "opt_two_id": 17,"opt_two_value": S },
...and so on
]}
现在,如何在添加更多 option_type 时动态管理它。例如。现在我们正在考虑 option_type = 1 和 option_type = 2,但将来如果再添加一个选项,那么 option_type = 3 也会出现在集合中。
那么,在那种情况下,如何使用键名来管理这个集合,那么到时候它会变成这样
{ "opt_one_id": 15, "opt_two_id": 14, "opt_three_id": 17 },
因此,添加或删除任何 option_type
都会对其进行相应管理。提前致谢 !!!
=== 更新了 ===
考虑这个 option_type 的基表
id option_type
-----------------
1 Colour
2 Size
因此,相应地它将生成如下组合15 (White) * 14 (M)
15 (White) * 17 (S)
15 (White) * 18 (L)
16 (Black) * 14 (M)
16 (Black) * 17 (S)
16 (Black) * 18 (L)
最佳答案
您可以使用 option_type
使用下划线对结果进行分组,如下所示。
const options = _.groupBy(records, record => record.option_type);
console.log(options);
分组后,您将获得以下结构。(考虑我们现在有第三个选项类型)options = {
1: [
{id: 15, product_id: 6, option_type: 1},
{id: 16, product_id: 6, option_type: 1}
],
2: [
{id: 14, product_id: 6, option_type: 2},
{id: 17, product_id: 6, option_type: 2 },
{id: 18, product_id: 6, option_type: 2 }
],
3: [
{id: 19, product_id: 6, option_type: 3},
]
}
之后,您可以组合使用 for..in 和 for 循环以获得所需的结果,如下所示const keys = Object.keys(options);
const rootItem = options[keys[0]];
delete options[keys[0]];
const finalResults = [];
for(let i =0; i< rootItem.length; i++) {
for (option in options) {
for (let j = 0; j<options[option].length; j++) {
let item = {};
item[`option_type_${rootItem[i].option_type}`] = rootItem[i].id;
item[`option_type_${options[option][j].option_type}`] = options[option][j].id;
finalResults.push(item);
}
}
}
console.log(finalResults)
[ { option_type_1: 15, option_type_2: 14 },
{ option_type_1: 15, option_type_2: 17 },
{ option_type_1: 15, option_type_2: 18 },
{ option_type_1: 15, option_type_3: 19 },
{ option_type_1: 16, option_type_2: 14 },
{ option_type_1: 16, option_type_2: 17 },
{ option_type_1: 16, option_type_2: 18 },
{ option_type_1: 16, option_type_3: 19 } ]
关于javascript - NodeJS : Create api that will manage to generate the for loop as dynamic based on key value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64334214/