2016-11-08 62 views
2

我有許多陣列,從csv文件生成。在所有的數組中,第一個數組對象是csv標題標題。見下面的例子:使用另一個陣列中的值轉換所有陣列鍵

enter image description here

因此,在總結,第一陣列的值(即,鍵= 0,值=「REPORT_DATE」)應更換所有後續陣列的所有鍵。

因此,對於除第一個之外的所有陣列都進行這樣的轉換。

Array[7] 
"report_date": "2014-01-07" 
"description": "Cupidatat reprehenderit anim non irure aliqua irure veniam sint veniam velit aute elit." 
"email": "[email protected]" 
"company": "Techtrix" 
"status": "false" 
"name/last": "Pennington" 
"name/first": "Helene" 

回答

1

這應該做的伎倆:

var data = [['id', 'name', 'value'], [0, 'foo', true], [2, 'bar', false], [3, 'baz', null], [4, 'foobar', undefined] ]; 
 

 
var keys = data.shift();  // Get the first row, containing the keys 
 
var result = data.map(function(row) { 
 
    var current = {};   // Create a new element 
 
    for (var i = 0; i < keys.length; i++) { 
 
    current[keys[i]] = row[i]; // Map the current row to keys on the new element 
 
    } 
 
    return current;    // Return the new element, to be used in the result. 
 
}); 
 

 
console.log(result);

記住shift修改源陣列。作爲此功能的結果,data變量會被編輯。

+0

不真正關心如果源陣列被修改。加工。謝謝 – Rexford

2

您可以將結果映射到對象並刪除第一個項目(只需鍵/鍵)。

var array = [["report_date", "description", "email", "company", "status", "name/last", "name/first"], ["2014-01-07", "Cupidatat reprehenderit anim non irure aliqua irure veniam sint veniam velit aute elit.", "[email protected]", "Techtrix", "false", "Pennington", "Helene"]], 
 
    result = array.map(function (a, _, aa) { 
 
     var object = {}; 
 
     aa[0].forEach(function (key, i) { 
 
      object[key] = a[i]; 
 
     }); 
 
     return object; 
 
    }).slice(1); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+1

謝謝。也有效。 – Rexford

0

另外一個解決您的問題的方法如下;

var data = [["prop_0", "prop_1", "prop_2"], 
 
      ["val_00", "val_01", "val_02"], 
 
      ["val_10", "val_11", "val_12"], 
 
      ["val_20", "val_21", "val_22"]], 
 
newData = data.slice(1) 
 
       .map(vs => vs.reduce((p,c,i) => i-1 ? Object.assign(p,{[data[0][i]]: c}) 
 
                : Object.assign({},{[data[0][i-1]]: p, [data[0][i]]: c}))); 
 
console.log(newData);