两个替换JS



你能推荐更优雅的处理这些情况的方法吗?

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const getCombinations = () => {
  const combinations = [];
  arr1.forEach(el1 => {
    arr2.forEach(el2 => {
      combinations.push({
        el1,
        el2
      });
    });
  });
  return combinations;
};
console.log(getCombinations());

您可以将Array.flatMap()Array.map() 一起使用:

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const getCombinations = (a, b) => 
  a.flatMap(el1 => b.map(el2 => ({ el1, el2 })));
const result = getCombinations(arr1, arr2);
console.log(result);

你可以通过先取笛卡尔积,然后用想要的属性映射对象来采取稍微动态的aproach。

const
    cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
    takeKeys = keys => a => Object.assign(...a.map((v, i) => ({ [keys[i]]: v })))
    array1 = [1, 2, 3],
    array2 = ['a', 'b', 'c'],
    result = [array1, array2]
        .reduce(cartesian)
        .map(takeKeys(['el1', 'el2']));
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新