在json中组合两个数组

时间:2018-01-25 10:38:17

标签: javascript arrays json recursion lodash

输入:

"options": [
  {
    "name": "Color",
    "values": [
      "Blue",
      "Black"
    ]
  },
  {
    "name": "Size",
    "values": [
      "Small",
      "Large"
    ]
  }
]

Output: "variants": [
  {
    "option1": "Blue",
    "option2": "Small"
  },
  {
    "option1": "Blue",
    "option2": "Large"
  },
  {
    "option1": "Black",
    "option2": "Small"
  },
  {
    "option1": "Black",
    "option2": "Large"
  }
]

如何使用递归来解决这个问题?options数组可以包含多个名称,我需要显示上面的内容。可以用笛卡尔积来做到吗

3 个答案:

答案 0 :(得分:2)

您可以使用嵌套Array.map()调用,创建对象,并使用Array.concat()展平子数组:

const options = [{"name":"Color","values":["Blue","Black"]},{"name":"Size","values":["155","159"]}]

const [{ values: colors }, { values: sizes }] = options
const result = [].concat(...colors.map((option1) => sizes.map((option2) => ({
  option1,
  option2
}))))

console.log(result)

答案 1 :(得分:1)

您可以采用迭代和递归方法来获取所有选项组合。

function getCombinations(array) {

    function iter(i, temp) {
        if (i === array.length) {
            result.push(temp.reduce(function (o, v, i) {
                o['option' + (i + 1)] = v;
                return o;
            }, {}));
            return;
        }
        array[i].values.forEach(function (a) {
            iter(i + 1, temp.concat(a));
        });
    }

    var result = [];
    iter(0, []);
    return result;
}

var options = [{ name: "Color", values: ["Blue", "Black"] }, { name: "Size", values: ["155", "159"] }, { name: 'Material', values: ['Sand', 'Clay', 'Mud'] }],
    variants = getCombinations(options);

console.log(variants);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

function getCombinations(array) {

    function iter(i, temp) {
        if (i === array.length) {
            result.push(temp);
            return;
        }
        array[i].values.forEach(a => iter(i + 1, Object.assign({}, temp, { ['option' + (i + 1)]: a })));
    }

    var result = [];
    iter(0, {});
    return result;
}

var options = [{ name: "Color", values: ["Blue", "Black"] }, { name: "Size", values: ["155", "159"] }, { name: 'Material', values: ['Sand', 'Clay', 'Mud'] }],
    variants = getCombinations(options);

console.log(variants);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

var myarray = {"options": [
  {
    "name": "Color",
    "values": [
      "Blue",
      "Black"
    ]
  },
  {
    "name": "Size",
    "values": [
      "155",
      "159"
    ]
  }
]};

const key = myarray.options[0].values;
const value =myarray.options[1].values;
const output = _.zipWith(key, value, (key, value)=> ({ key, value }));
console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js"></script>