题目描述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个数组)有什么更好的办法。
1 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
动态传入数组,动态计算 key,即可,代码如下:
const arr1 = [1, 2, 3, 4, 5];const arr2 = ['a1', 'a2', 'a3', 'a4', 'a5'];const arr3 = ['b1', 'b2', 'b3', 'b4', 'b5'];const arr4 = ['c1', 'c2', 'c3', 'c4', 'c5'];const arr5 = [11, 22, 33, 44, 55];function parse (...arrList) { const result = [] for (let i = 0, l = arrList.length, arr, key; i < l; i++) { arr = arrList[i] key = String.fromCharCode(97 + i) for (let j = 0, l = arr.length; j < l; j++) { if (!result[j]) { result[j] = {} } result[j][key] = arr[j] } } return result } parse(arr1, arr2, arr3, arr4, arr5)
添加回答
举报
0/150
提交
取消