Home > Software design >  nested array to object javascript
nested array to object javascript

Time:02-14

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);

CodePudding user response:

input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
obj = {}

const convert = (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;
        }
    })
};
convert(input);
console.log(obj);

CodePudding user response:

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, obj={};
  for (let i = 0; i < arr.length; i  ){
    if(!Array.isArray(arr[i])){
        obj[arr[i]] = arr[i];
    } else obj["array" (  n)]=convert(arr[i]);        
  }
  return obj;
 }
 console.log( convert(input) );

  • Related