代码之家  ›  专栏  ›  技术社区  ›  Treycos

将数组映射为以奇数元素为键,偶数元素为值的对象

  •  1
  • Treycos  · 技术社区  · 6 年前

    这个标题应该是不言自明的。如何转动以下阵列:

    [
      "Bargain",
      "deal",
      "Consistent",
      "Steady; regular",
      "Accurately",
      "a thing bought or offered for sale much more cheaply than is usual or expected.",
      "Charge",
      "demand (an amount) as a price for a service rendered or goods supplied."
    ]
    

    进入下面的数组:

    [
        {"Bargain": "deal"},
        {"Consistent": "Steady; regular"},
        {"Accurately": "a thing bought or offered for sale much more cheaply than is usual or expected."},
        {"Charge": "demand (an amount) as a price for a service rendered or goods supplied."}
    ]
    

    解决方案可能很简单,但我找不到一个简单的方法来实现它。我试着制作两个独立的数组,在合并之前先去掉第一个数组中的奇数和第二个数组中的偶数,然后再过滤每个数组中的元素,但这看起来太过分了。

    有没有一个简单的方法来实现它?

    (是的,我知道“准确”的定义是……怪异的)

    2 回复  |  直到 6 年前
        1
  •  2
  •   adiga    6 年前

    你可以使用 Array.from 这样地:

    const input = [
      "Bargain",
      "deal",
      "Consistent",
      "Steady; regular",
      "Accurately",
      "a thing bought or offered for sale much more cheaply than is usual or expected.",
      "Charge",
      "demand (an amount) as a price for a service rendered or goods supplied."
    ]
    
    const length = Math.ceil(input.length / 2)
    
    const output = Array.from({ length }, (_, i) =>
       ({ [input[i*2]]: input[i*2+1] })
      );
      
    console.log(output)
        2
  •  6
  •   Taki    6 年前

    你可以用一个简单的 for 循环:

    const data = [
      "Bargain",
      "deal",
      "Consistent",
      "Steady; regular",
      "Accurately",
      "a thing bought or offered for sale much more cheaply than is usual or expected.",
      "Charge",
      "demand (an amount) as a price for a service rendered or goods supplied."
    ];
    
    let result = [];
    
    for (let i = 0; i < data.length; i += 2) {
      result.push({
        [data[i]]: data[i + 1]
      });
    }
    
    console.log(result);