js多个数组(3个以上)如何合并成json形式

题目描述

arr1 = [1, 2, 3, 4, 5];
arr2 = [a1, a2, a3, a4, a5];
arr3 = [b1, b2, b3, b4, b5];
arr4 = [c1, c2, c3, c4, c5];
arr5 = [11, 22, 33, 44, 55];
多个数组类似这个形式,数组里内容是不定的
需要合并成这个形式
[
{ "a": "1", "b": "a1", "c": "b1", "d": "c1", "e":"11" }, 
{ "a": "2", "b": "a2", "c": "b2", "d": "c2", "e":"22" }, 
{ "a": "3", "b": "a3", "c": "b3", "d": "c3", "e":"33" }, 
{ "a": "4", "b": "a4", "c": "b4", "d": "c4", "e":"44" }, 
{ "a": "5", "b": "a5", "c": "b5", "d": "c5", "e":"55" }
]

两个数组 我用的2个for循环嵌套 和if语句判断 push到对象里
如果更多(5-6个数组)有什么更好的办法。


手掌心
浏览 470回答 1
1回答

慕桂英546537

动态传入数组,动态计算 key,即可,代码如下:const&nbsp;arr1&nbsp;=&nbsp;[1,&nbsp;2,&nbsp;3,&nbsp;4,&nbsp;5];const&nbsp;arr2&nbsp;=&nbsp;['a1',&nbsp;'a2',&nbsp;'a3',&nbsp;'a4',&nbsp;'a5'];const&nbsp;arr3&nbsp;=&nbsp;['b1',&nbsp;'b2',&nbsp;'b3',&nbsp;'b4',&nbsp;'b5'];const&nbsp;arr4&nbsp;=&nbsp;['c1',&nbsp;'c2',&nbsp;'c3',&nbsp;'c4',&nbsp;'c5'];const&nbsp;arr5&nbsp;=&nbsp;[11,&nbsp;22,&nbsp;33,&nbsp;44,&nbsp;55];function&nbsp;parse&nbsp;(...arrList)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;result&nbsp;=&nbsp;[]&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(let&nbsp;i&nbsp;=&nbsp;0,&nbsp;l&nbsp;=&nbsp;arrList.length,&nbsp;arr,&nbsp;key;&nbsp;i&nbsp;<&nbsp;l;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arr&nbsp;=&nbsp;arrList[i] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key&nbsp;=&nbsp;String.fromCharCode(97&nbsp;+&nbsp;i)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(let&nbsp;j&nbsp;=&nbsp;0,&nbsp;l&nbsp;=&nbsp;arr.length;&nbsp;j&nbsp;<&nbsp;l;&nbsp;j++)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!result[j])&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result[j]&nbsp;=&nbsp;{} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result[j][key]&nbsp;=&nbsp;arr[j] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;result } parse(arr1,&nbsp;arr2,&nbsp;arr3,&nbsp;arr4,&nbsp;arr5)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript