js怎么将一个二维数组转换成对象?

二维数组的格式如下:

[["num1","num2","num3","num4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"]];

要求将使用索引为0的每一项作为key值,
后面对应的位置的字符作为value。

输出的格式为:

{
    num1:["1","1","1","1"],
    num2:["2","2","2","2"],
    num3:["3","3","3","3"],
    num4:["4","4","4","4"]
}

求助,该这么转换啊?

先感谢。


clipboard.png

阅读 10k
3 个回答

这不就是一个二重循环的事儿吗?

var arr = [
    ["num1", "num2", "num3", "num4"],
    ["1", "2", "3", "4"],
    ["1", "2", "3", "4"],
    ["1", "2", "3", "4"],
    ["1", "2", "3", "4"]
];

var keys = arr.shift();

const result = keys.reduce((obj, key, i) => {
    obj[key] = arr.map(a => a[i]);
    return obj;
}, {});

console.log(result);

10月16日补充说明:

前提是,大数据中每个小数组的长度是一样的(如果不一样需要做容错处理),然后把这个长度取出来作为大循环的长度。之所以这样做,是因为把结果和源数据都看作矩阵的话,它们之间是个转置的关系。

接下来,大循环只能从 1 开始,而不能从 0 开始,因为第 0 项是 key,后面的各项组合起来才是 value。这就是上面把 keys 单独取出来的原因(按正常逻辑是转置后取,对这个问题来说,转置前取更方便,而后取了之后,后面的部分就可以从 0 开始索引了)

剩下的事情就简单了,用个循环把 value 拼出来就好。

上面的代码采用了 reduce 和 map,整个过程实际是把转置和处理混在一起的。建议你自己思考一下如何按逻辑一步步来处理,不考虑优化整合的问题,用一个二重循环把它实现出来(也就是这段说明提到的思路),然后自己给自己回答个。

var arr = [["num1","num2","num3","num4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"]];
var obj = {};
for(var i = 1; i < arr.length; i++) {
    obj[arr[0][i-1]] = arr[i];
}
console.log(obj);

不改变原数组的做法,可能有跟简单的做法

    const crr=[["num1","num2","num3","num4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"],["1","2","3","4"]];
    const drr=crr.reduce((pre,cur,i,arr)=>{
        if(i===4) return pre
        pre[arr[0][i]]=arr.reduce((pre1,cur1,j)=>{
            if(j===0) return pre1
            return pre1.concat(cur1[i])
        },[])
        return pre
    },{})
    console.log(crr,drr)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏