Javascript - convert array of arrays into array of objects with prefilled values

后端 未结 4 820
北荒
北荒 2020-11-27 08:07

I have following array:

[
    [val1, val2]
    [val1, val2]
    [val1, val2]
    [valN, valN]
]

N represents the fact that the

相关标签:
4条回答
  • 2020-11-27 08:40

    You can simply use Array.prototype.map to project an array into another one by applying a projection function:

    var arrs = [
        [1, 2],
        [3, 4],
        [5, 6],
        [7, 8]
    ];
    
    var objs = arrs.map(function(x) { 
      return { 
        lat: x[0], 
        lng: x[1] 
      }; 
    });
    console.log(objs);

    0 讨论(0)
  • 2020-11-27 08:42

    Using ES6 you can write this in a very concise way:

    var arrs = [
        [1, 2],
        [3, 4],
        [5, 6],
        [7, 8]
    ];
    const locations = arrs.map(([lat, lng]) => ({lat, lng}));
    console.log(locations);

    0 讨论(0)
  • 2020-11-27 08:55

    var array = [
        ['val1', 'val2'],
        ['val1', 'val2'],
        ['val1', 'val2'],
        ['valN', 'valN']
    ];
    
    var arrayObject = array.map(function(item){ 
      return { lat: item[0], lng: item[1]};
    });
    
    console.log(arrayObject);

    0 讨论(0)
  • 2020-11-27 08:56

    You can use Array#map to achieve this. Array#map passes each array element through a projection function and returns the values in a new array.

    var data= [
        ['val1', 'val2'],
        ['val1', 'val2'],
        ['val1', 'val2'],
        ['valN', 'valN'],
    ];
    
    var result = data.map(function(row) {
      return {
        lat: row[0],
        lng: row[1]
      };
    });
    
    console.log(result);

    0 讨论(0)
提交回复
热议问题