代码之家  ›  专栏  ›  技术社区  ›  Cheryl Blossom

将数组的数组转换为具有键的对象

  •  10
  • Cheryl Blossom  · 技术社区  · 7 年前

    我有数组的数组,其中包含如下内容:

    var values = [[1, 2, 3], [3, 2, 1]]
    

    我试过.map()和Object.assign,但不知道如何实现它。我想把它作为一个输出:

    values = [
        {'up': 1, 'middle': 2, 'down': 3},
        {'up': 3, 'middle': 2, 'down': 1}
    ]
    

    我应该用什么?到目前为止,我是这么想的:

    const object1 = [[1,2,3],[3,2,1]],
      object = []
    
    object1.forEach(function(array) {
       object.map(value => ({'up': array[0], 'mid': array[1], 'down': array[2]}))
     });
    
    console.log(object)
    
    2 回复  |  直到 7 年前
        1
  •  13
  •   Amit    7 年前

    与其他人的做法没有太大区别,但要优雅一点:

    let arr = [[1, 2, 3], [3, 2, 1]];
    
    let result = arr.map(([up, middle, down]) => ({up, middle, down}));
    console.log(result);
        2
  •  3
  •   amrender singh    7 年前

    Array.map() forEach()

    let arr =[[1, 2, 3], [3, 2, 1]];
    
    let result = arr.map((e)=>({"up" : e[0], "mid"  : e[1], "down" : e[2]}));
    console.log(result);