我有一个看起来像这样的数组
var myArray = [
['a', 1],
['b', 2],
['c', 3]
]
我想将它转换为一个对象,它应该等于下面:
var myObj = {
'a' : 1,
'b' : 2,
'c' : 3
}
什么是更容易和更安全的(如果出现意外输入)的方式呢?
更新: 为了详细说明“更安全”,有时我可能会得到不同的输入,如
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' : ''
}
答案 0 :(得分:3)
您可以使用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, 3 ,1],
['d']
]
var result = myArray.reduce((r, e) => {
r[e[0]] = (e[1]) ? ((e.length > 2) ? e.slice(1) : e[1]) : '';
return r;
} , {});
console.log(result)
答案 1 :(得分:1)
var myArray = [
['a', 1],
['b', 2],
['c', 3]
];
var myObj = {};
myArray.forEach(function(element){
myObj[element[0]] = element[1];
})
答案 2 :(得分:1)
只需使用forEach填充myObj:
var myArray = [
['a', 1],
['b', 2],
['c', 3]
];
var myObj = {};
myArray.forEach(x => myObj[x[0]]=x[1]);
console.log(myObj);

答案 3 :(得分:0)
其他答案都没有处理意外输入......执行此操作的方法是使用.reduce()
和类型检查。
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));