数组交叉

    var field = ['color', 'size', 'type', 'type2', 'season'];
    var arr = [
        {name: '颜色', value: ['red', 'green']},
        {name: '尺码', value: ['L', 'M', 'XL']},
        {name: '类型', value: ['男款', '女款', '人妖款']},
        {name: '类型2', value: ['上衣', '裤子', '帽子', '袜子']},
        {name: '季节', value: ['春', '夏', '秋', '冬']},
    ];

    arr = arr.map(({value: v}, i) => v.map(t => Object({[field[i]]: t})));

    var result = arr
        .reduce((a, b) =>
            a.reduce((c, d) =>
                c.concat(b.map(e => Object.assign({}, d, e))), []));

    console.log(result);
 console.time('start');
  var field = ['color', 'size', 'type', 'type2', 'season'];
  var arr = [
    { name: '颜色', value: ['red', 'green'] },
    { name: '尺码', value: ['L', 'M', 'XL'] },
    { name: '类型', value: ['男款', '女款', '人妖款'] },
    { name: '类型2', value: ['上衣', '裤子', '帽子', '袜子'] },
    { name: '季节', value: ['春', '夏', '秋', '冬'] },
  ];

  function overlapping(a, b) {
    if (a.length === 0) {
      return b;
    }
    if (b.length === 0) {
      return a;
    }

    let newArr = [];

    a.forEach(v => {
      b.forEach(w => {
        newArr.push(v + '|' + w)
      })
    })

    return newArr
  }

  const result = arr.reduce((v, w) => overlapping(v, w.value), []).map(v => {
    let _v = v.split('|');
    let obj = {};
    field.map((x, i) => obj[x] = _v[i])
    return obj;
  })
  console.log(result);
  console.timeEnd('start');

 

你可能感兴趣的:(js)