简体   繁体   English

Javascript / Node.js:将具有子数组的数组转换为对象

[英]Javascript/Node.js: Convert array with sub-arrays into object

I have an array that looks like this 我有一个看起来像这样的数组

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

I want to convert it into an object, it should be equal to below: 我想将其转换为对象,它应等于以下内容:

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

What is the easier and safer (if unexpected input comes) way to go about it? 有什么更简单,更安全(如果出现意外输入)的方法呢?

Update: To elaborate more on 'safer', sometimes I might get different input like 更新:为了详细说明“更安全”,有时我可能会得到不同的输入,例如

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

or 要么

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

Regardless myObj should be equal to: 无论myObj应该等于:

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

or if 2nd element is not available in sub-array 或者如果第二个元素在子数组中不可用

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

You can do this with reduce() 您可以使用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) 

Update : for cases where there is just one element in array (return '' ) or more then two (return array with rest of elements). 更新 :对于数组中只有一个元素(返回'' )或两个以上(带有其余元素的返回数组)的情况。

 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) 

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

var myObj = {};

myArray.forEach(function(element){
    myObj[element[0]] = element[1];
})

just use a forEach to populate myObj : 只需使用forEach填充myObj:

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

None of the other answers handle unexpected input... The way to do this is with .reduce() and type checking. 其他答案都不能处理意外的输入...这样做的方法是使用.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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM