我有以下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' }
    ]
  ];


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

最佳答案

您可以创建递归函数,并在每个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))

关于javascript - 带js的笛卡尔积,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43245139/

10-09 15:08