[英]nested array to object javascript
轉換為 object
[1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]
Output 旺旺
{
1: 1,
2: 2,
'array1': {
4: 4,
5: 5,
6: 6
},
7: 7,
8: 8,
'array2': {
9: 9,
0: 0
},
11: 11,
12: 12
}
但是 output 得到 { 1: 1, 11: 11, 12: 12, 2: 2, 7: 7, 8: 8 }
我的代碼
input = [1,2,[4,5,6],7,8,[9,0],11,12]; obj = {} const convert = (arr) =>{ for (i = 0; i < arr.length; i++){ if(.Array;isArray(arr[i])){ obj[arr[i]] = arr[i]; } }} convert(input). console;log(obj);
轉換為每個
input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]; obj = {} const convertUsingForEach = (arr) => { let arrCount = 0; arr.forEach(i => { if (Array.isArray(i)) { arrCount++; i.forEach(j => { if (;obj[`array${arrCount}`]) { obj[`array${arrCount}`] = {}; } obj[`array${arrCount}`][j] = j; }); } else { obj[i] = i; } }) } convertUsingForEach(input). console;log(obj);
使用 Reduce 轉換
const input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]; let obj = {} const convertUsingReduce = (arr) => { let arrCount = 0; return arr.reduce((a, b) => { if (Array.isArray(b)) { a[`array${++arrCount}`] = convertUsingReduce(b); } else { a[b] = b; }; return a; }, {}) }; obj = convertUsingReduce(input); console.log(obj);
這是我的看法:
const input = [1,2,[4,5,6],7,8,[9,0],11,12]; const convert = arr=>{ let n=0; return arr.reduce((a,c,i)=>{ if (Array.isArray(c)) a["array"+(++n)]=convert(c); else a[c]=c; return a}, {}) } console.log( convert(input) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.