gpt4 book ai didi

javascript - 在 Javascript 中将数据从一种形状转换为另一种形状

转载 作者:行者123 更新时间:2023-11-29 18:50:10 27 4
gpt4 key购买 nike

我将如何使用 Javascript(es6 很好)转换下面的这种数据形状。

来自:

[
{
name: "Color",
options: [{ value: "Gold" }, { value: "Space grey" }]
},
{
name: "Size",
options: [{ value: 32 }, { value: 64 }]
},
{
name: "Width",
options: [{ value: 100 }, { value: 200 }]
}
]

收件人:

[
{
properties: {
Color: "Gold",
Size: 32,
Width: 100
}
},
{
properties: {
Color: "Gold",
Size: 32,
Width: 200
}
},
{
properties: {
Color: "Gold",
Size: 64,
Width: 100
}
},
{
properties: {
Color: "Gold",
Size: 64,
Width: 200
}
},
{
properties: {
Color: "Space grey",
Size: 32,
Width: 100
}
},
{
properties: {
Color: "Space grey",
Size: 32,
Width: 200
}
},
{
properties: {
Color: "Space grey",
Size: 64,
Width: 100
}
},
{
properties: {
Color: "Space grey",
Size: 64,
Width: 200
}
}
]

第二个形状是第一个形状选项的所有可能组合。

我正在尝试构建一个可以处理具有变体的产品的产品表单,例如颜色、尺寸、 Material 等。这些变体中的每一个都可以有多个选项。例如对于颜色,它们可以是红色、蓝色、橙色等。为了让它工作,我想我需要一个列表来生成所有可能的组合,以便我可以为每个组合定价。

如有任何帮助,我将不胜感激 :(

下面是我试过的。但它的形状不对。

let variants = [{
name: "Color",
options: [{
value: "Gold"
}, {
value: "Space grey"
}]
},
{
name: "Size",
options: [{
value: "32"
}, {
value: "64"
}]
},
{
name: "Width",
options: [{
value: "100"
}, {
value: "200"
}]
}
]

const [primaryOption, ...otherOptions] = variants

let options = []
primaryOption.options.map(x => {
otherOptions.map(y => {
y.options.map(z => {
options = [
...options,
{
properties: {
[primaryOption.name]: x.value,
[y.name]: z.value
}
}
]
})
})
})

console.log(options)

最佳答案

 let result = [{}];

for(const {name, options} of input) {
const previous = result;
result = [];
for(const {value} of options) {
for(const prev of previous)
result.push({ ...prev, [name]: value });
}
}

只需使用嵌套循环遍历所有值,并用它们构建一个新数组。

关于javascript - 在 Javascript 中将数据从一种形状转换为另一种形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51496227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com