convert to object
[1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]
Output want
{
1: 1,
2: 2,
'array1': {
4: 4,
5: 5,
6: 6
},
7: 7,
8: 8,
'array2': {
9: 9,
0: 0
},
11: 11,
12: 12
}
but output get { 1: 1, 11: 11, 12: 12, 2: 2, 7: 7, 8: 8 }
my code
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);
Convert Using For Each
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);
Convert Using 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);
Here is my take on it:
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) );