与js的笛卡尔积

时间:2017-04-06 03:25:59

标签: javascript jquery

我有以下js输入,一个json对象数组selectSpec

 var selectSpec = [
    {
      attr: [{ 'memory': 20 }],
      attrValues:[
        { attrValueName: '16G', attrValueId: 21 },
        { attrValueName: '32G', attrValueId: 22 }
      ]
    },
    {
      attr: [{ 'color': 27 }],attrValues:
      [
        { attrValueName: 'white', attrValueId: 23 },
        { attrValueName: 'black', attrValueId: 34 }
      ]
    }
  ];

我需要输出以下数据,

var selectResult = [
    [
      { attrId: 20, attrValueId: 21, attrValueName: '16G' },
      { attrId: 27, attrValueId: 23, attrValueName: 'white' }
    ],
    [
      { attrId: 20, attrValueId: 21, attrValueName: '16G' },
      { attrId: 27, attrValueId: 34, attrValueName: 'black' }
    ],
    [
      { attrId: 20, attrValueId: 22, attrValueName: '32G' },
      { attrId: 27, attrValueId: 23, attrValueName: 'black' }
    ],
    [
      { attrId: 20, attrValueId: 22, attrValueName: '32G' },
      { attrId: 27, attrValueId: 34, attrValueName: 'white' }
    ]
  ];

我尝试使用笛卡尔积,但最后,它仍然存在一些问题,我不知道如何实现它。提前谢谢。

1 个答案:

答案 0 :(得分:3)

您可以为每个for创建递归函数和内部使用attrValues循环,并为数组中的每个对象增加一个值。



var selectSpec = [{"attr":[{"memory":20}],"attrValues":[{"attrValueName":"16G","attrValueId":21},{"attrValueName":"32G","attrValueId":22}]},{"attr":[{"color":27}],"attrValues":[{"attrValueName":"white","attrValueId":23},{"attrValueName":"black","attrValueId":34}]}];

function cartesian(data) {
  var r = [];

  function generate(data, n, c) {
    if (n == data.length) {
      return r.push(c.slice());
    }

    var value = data[n].attr[0][Object.keys(data[n].attr[0])[0]]

    for (var i = 0; i < data[n].attrValues.length; i++) {
      c[n] = Object.assign({}, {
        attrId: value
      }, data[n].attrValues[i])
      generate(data, n + 1, c);
    }
  }

  generate(data, 0, []);
  return r;
}

console.log(JSON.stringify(cartesian(selectSpec), 0, 4))
&#13;
&#13;
&#13;