用Javascript将数据从一种形状转换为另一种形状



我该如何使用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
}
}
]

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

我正在尝试构建一个产品表单,该表单可以处理具有变体的产品,例如颜色、尺寸、材料等。每个变体都可以有多个选项。例如,对于颜色,它们可以是红色、蓝色、橙色等。为了实现这一点,我想我需要一个生成所有可能组合的列表,这样我就可以为每个组合附上价格。

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

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

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 });
}
}

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

let variants = [{
name: "Color",
options: [{
value: "Gold"
}, {
value: "Space grey"
}]
},
{
name: "Size",
options: [{
value: 32
}, {
value: 64
}]
},
{
name: "Width",
options: [{
value: 100
}, {
value: 200
}]
}
];
let endIndex = variants[0].options.length;
let result = [];
for (let i = 0; i < endIndex; i++) {
variants.forEach(x => {
result[i] = result[i] || {properties:{}};
result[i].properties[x.name] = x.options[i].value;
});
}
console.log(result);

您可以通过迭代外部数组来获得笛卡尔乘积,并使用内部数组来获得要附加对象的值。

function getCartesian(array) {
return array.reduce((r, { name, options }) => {
var temp = [];
r.forEach(({ property }) =>
options.forEach(({ value }) => temp.push({ property: Object.assign({}, property, { [name]: value }) }))
);
return temp;
}, [{}]);
}
var data = [{ name: "Color", options: [{ value: "Gold" }, { value: "Space grey" }] }, { name: "Size", options: [{ value: 32 }, { value: 64 }] }, { name: "Width", options: [{ value: 100 }, { value: 200 }] }];
console.log(getCartesian(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关内容

最新更新