Javascript将数组项目与其他数组中的每个项目组合为文本

时间:2018-11-10 16:38:55

标签: javascript arrays

我有这个数组; ["Color", ["red", "blue"]]

我想将颜色数组的项目与这些数组中的项目合并为文本;

[
 ["Size", ["small", "medium", "large"]],
 ["Model", ["modern", "old"]]
]

最终结果应该是这样;

[
 "Color_red_Size_small_Model_modern",
 "Color_red_Size_small_Model_old",
 "Color_red_Size_medium_Model_modern",
 "Color_red_Size_medium_Model_old",
 "Color_red_Size_large_Model_modern",
 "Color_red_Size_large_Model_old",
 "Color_blue_Size_small_Model_modern",
 "Color_blue_Size_small_Model_old",
 "Color_blue_Size_medium_Model_modern",
 "Color_blue_Size_medium_Model_old",
 "Color_blue_Size_large_Model_modern",
 "Color_blue_Size_large_Model_old",
]

我做不到。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以对值采用笛卡尔函数并将键映射到值的前面,然后遍历数组。

for i in arduino_mega2560 arduino_leonardo arduino_uno breakout_32u2 arduino_promicro; do make --directory=$i clean; make --directory=$i all; done
i was unexpected at this time.
makefile:5: recipe for target 'all' failed
make: *** [all] Error 255
const
    cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
    data = [["Color", ["red", "blue"]], ["Size", ["small", "medium", "large"]], ["Model", ["modern", "old"]]],
    keys = data.map(([key]) => key),
    result = data
        .map(([, values]) => values)
        .reduce(cartesian)
        .map(a => a.map((v, i) => [keys[i], v].join('_')).join('_'));

console.log(result);

答案 1 :(得分:0)

尝试

function makeLabels (arr) {
  return arr.reduce((result, el) => {
    var first = el[0];
    var list = el[1];
    var newResult = [];
    if (result.length < 1) {
      list.forEach((val) => {
        newResult.push(first+"_"+val);
      });
    } else {
      result.forEach((r) => {
      
        list.forEach((val) => {
          newResult.push(r+"_"+first+"_"+val);
        });
      });
    }
    return newResult;
  }, []);
}

var properties =
  [ ["Color", ["red", "blue"]]
  , ["Size", ["small", "medium", "large"]]
  , ["Model", ["modern", "old"]] ];
  
console.log( makeLabels(properties) );