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

使用Javascript将列表转换为字典列表

  •  0
  • JokerMartini  · 技术社区  · 4 年前

    有没有一种内置的方法,使用javascript,将一个列表列表转换成一个字典列表?

    以前

    [
       [
          "x", 
          "y", 
          "z",  
          "total_count", 
          "total_wins"
       ], 
       [
          25.18, 
          24.0, 
          27520.0, 
          16, 
          6, 
       ], 
       [
          25.899, 
          24.0, 
          27509.0, 
          336, 
          8
       ], 
       [
          26.353, 
          26.0, 
          27256.0, 
          240.0, 
          15 
       ], 
       [
          119.0, 
          5.0, 
          6.0, 
          72, 
          0
       ]
    ]
    

    之后

    [
       {
          "x": 25.18, 
          "y": 24.0, 
          "z": 27520.0, 
          "total_count": 16, 
          "total_wins": 6, 
       }, 
       {
          "x": 25.899, 
          "y": 24.0, 
          "z": 27509.0, 
          "total_count": 336, 
          "total_wins": 8
       }, 
       {
          "x": 26.353, 
          "y": 26.0, 
          "z": 27256.0, 
          "total_count": 240.0, 
          "total_wins": 15 
       }, 
       {
          "x": 119.0, 
          "y": 5.0, 
          "z": 6.0, 
          "total_count": 72, 
          "total_wins": 0
       }
    ]
    
    2 回复  |  直到 4 年前
        1
  •  2
  •   ponury-kostek    4 年前

    也许不是内置的,但是有一种方法

    const input = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];
    
    const keys = input.shift();
    console.log(input.map(values => Object.fromEntries(keys.map((key, idx) => [
    	key,
    	values[idx]
    ]))));
        2
  •  0
  •   Code Maniac    4 年前

    rest operator, map and Object.fromEntries

    let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];
    
    let [keys, ...rest] = data
    
    let final = rest.map(inp => Object.fromEntries(inp.map((value, index) => [keys[index], value])))
    
    console.log(final)

    如果您正在处理不支持Object.fromEntries的环境,则可以使用reduce

    let data = [["x", "y", "z", "total_count", "total_wins"], [25.18, 24.0, 27520.0, 16, 6,], [25.899, 24.0, 27509.0, 336, 8], [26.353, 26.0, 27256.0, 240.0, 15], [119.0, 5.0, 6.0, 72, 0]];
    
    let [keys, ...rest] = data
    
    let buildObject = (valueArr) => {
      return valueArr.reduce((op, inp, index) => {
        op[keys[index]] = inp
        return op
      }, {})
    }
    
    let final = rest.map(inp => buildObject(inp, keys))
    
    console.log(final)