首页 > 解决方案 > 对象数组和数组列表。需要得到组合;

问题描述

我需要得到这个的所有组合

我的结构如下,

   [
      {
         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 的递归循环。不幸的是,我还在考虑算法。谁能帮我这个。

标签: javascriptalgorithm

解决方案


由于我们不在 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>


推荐阅读