javascript - 对象数组和数组列表。需要得到组合;
问题描述
我需要得到这个的所有组合
我的结构如下,
[
{
propertyId: 1,
options: [
{
id: 101,
price: 100
},
{
id: 102,
price: 200
}
]
},
{
propertyId: 2,
options: [
{
id: 201,
price: 300
},
{
id: 202,
price: 400
}
]
}
]
我需要获取所有属性组合。
结果:
[
{
price: 400,
properties: [
{
propertyId: 1,
optionId: 101,
},
{
propertyId: 2,
optionId: 201,
}
]
},
{
price: 500,
properties: [
{
propertyId: 1,
optionId: 101,
},
{
propertyId: 2,
optionId: 202,
}
]
},
{
price: 500,
properties: [
{
propertyId: 1,
optionId: 102,
},
{
propertyId: 2,
optionId: 201,
}
]
},
{
price: 600,
properties: [
{
propertyId: 1,
optionId: 102,
},
{
propertyId: 2,
optionId: 202,
}
]
}
以及所有其他组合(100+300、100+400、200+300、200+400...等)
我想我需要使用 forof 的递归循环。不幸的是,我还在考虑算法。谁能帮我这个。
解决方案
由于我们不在 PHP 中,所以正常for
对我们有好处:
const input = [{
propertyId: 1,
options: [{
id: 101,
price: 100
},
{
id: 102,
price: 200
}
]
},
{
propertyId: 2,
options: [{
id: 201,
price: 300
},
{
id: 202,
price: 400
}
]
}
];
const result = [];
function process2properties(property1, property2) {
for (let option1 of property1.options) {
for (let option2 of property2.options) {
result.push({
price: option1.price + option2.price,
properties: [
{propertyId: property1.propertyId, optionId: option1.id},
{propertyId: property2.propertyId, optionId: option2.id},
]
});
}
}
}
for (let i = 0; i < input.length; i++) {
const property = input[i];
for (let j = i + 1; j < input.length; j++) {
const anotherProperty = input[j];
process2properties(property, anotherProperty);
}
}
document.getElementById('result').innerHTML = JSON.stringify(result, null, ' ');
<pre id="result"></pre>
推荐阅读
- pdf - 是否可以自动检查 PDF 是否遵循 PDF/UA 标准?
- shell - 如何在期望脚本的发送中使用 shell 命令的输出
- sql - SQL:根据表中保存的计算对每一行进行不同的计算
- android - 打开应用程序后 Flutter 崩溃
- python - 在 Vagrant 中安装 django-cron 时权限被拒绝
- db2 - DB2:LUW:Windows(OS) 无法调用 Java UDF
- pandas - 更改熊猫数据框的架构
- angular - 如何避免两次调用观察方法?
- python - 请求翻译时似乎未使用上传的词汇表
- c++ - 带有 C++ Builder 10.x 的 FASTMM 调试版本