Javascript / Node.js:将数组与子数组转换为对象

我有一个看起来像这样的数组

var myArray = [ ['a', 1], ['b', 2], ['c', 3] ] 

我想把它转换成一个对象,它应该等于如下:

 var myObj = { 'a' : 1, 'b' : 2, 'c' : 3 } 

什么是更容易和更安全(如果意想不到的input)的方式去呢?

更新:为了更详细地阐述“更安全”,有时我可能会得到不同的input

 var myArray = [ ['a', 1], ['b', 2], ['c', 3, 4, 5] ] 

要么

 var myArray = [ ['a', 1], ['b', 2], ['c', 3], ['d'] ] 

无论myObj应该等于:

 var myObj = { 'first-key' : 'firts-value' } 

或者第二个元素在子数组中不可用

 var myObj = { 'first-key' : '' } 

没有其他的答案处理意外的input…做到这一点的方式是使用.reduce()和types检查。

 var myArray = [ [[1, 2, 3], 'a'], // [1] is valid property name, [0] valid value ['b', 2, 5, 2], // [0] is valid property name, [1] valid value ['c', undefined], // [0] is valid property name, [1] invalid value { prop1: "123" }, // Invalid - is not an array undefined, // Invalid - is not an array 123, // Invalid - is not an array [undefined, 'd'], // [1] is valid property name, [0] valid value ['e'] // [0] is valid property name, [1] does not exist ]; function convertArrToObj(arr) { // check to ensure that parent is actually an array if (isArray(arr)) { return arr.reduce(function(obj, curr) { // check to ensure each child is an array with length > 0 if (isArray(curr) && curr.length > 0) { // if array.length > 1, we are interested in [0] and [1] if (curr.length > 1) { // check if [0] is valid property name if (typeof curr[0] === "string" || typeof curr[0] === "number") { // if so, use [0] as key, and [1] as value obj[curr[0]] = curr[1] || "" } // if not, check if [1] is a valid property name else if (typeof curr[1] === "string" || typeof curr[1] === "number") { // if so, use [1] as key, and [0] as value obj[curr[1]] = curr[0] || "" } // if no valid property names found, do nothing } else { // if array.length === 1, check if the one element is // a valid property name. if (typeof curr[0] === "string" || typeof curr[0] === "number") { // If so, add it and use "" as value obj[curr[0]] = ""; } } } // return updated object for next iteration return obj }, {}); } } function isArray(val) { return val === Object(val) && Object.prototype.toString.call(val) === '[object Array]'; } console.log(convertArrToObj(myArray)); 

你可以用reduce()来做到这一点

 var myArray = [ ['a', 1], ['b', 2], ['c', 3] ] var result = myArray.reduce((r, e) => { r[e[0]] = e[1]; return r; } , {}); console.log(result) 
 var myArray = [ ['a', 1], ['b', 2], ['c', 3] ]; var myObj = {}; myArray.forEach(function(element){ myObj[element[0]] = element[1]; }) 

只需使用forEach来填充myObj:

 var myArray = [ ['a', 1], ['b', 2], ['c', 3] ]; var myObj = {}; myArray.forEach(x => myObj[x[0]]=x[1]); console.log(myObj);