Home > OS >  I want to create an object from an array which has subarray also
I want to create an object from an array which has subarray also

Time:01-12

This is my input:

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];

output what I want:

{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}

CodePudding user response:

my approach using Array.prototype.reduce(). only handles 1 level nested array.

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];
let count=1;

let a = arr.reduce((acc,curr) => {

    if(Array.isArray(curr)){
    let b = curr.reduce((acc1,curr1)=> {
        acc1[curr1] = curr1;
      return acc1
    },{})
    acc[`array${count}`] = b;
    count =1;
  }
  else{
    acc[curr] = curr;
  }
 
  return acc;

},{})

console.log(a)

Since it is an object it necessarily doesn't have to be in the order you have given.

CodePudding user response:

Simply loop through the array, formatting a new object as you go:

let array_count = 1;
let obj = {}

arr.forEach((el) => {
  if(Number.isInteger(el)){
    obj[el] = el;
  } else {
    inline_obj = {}
    el.forEach((e2) => inline_obj[e2] = e2);
    obj[`array${array_count}`] = inline_obj;
    array_count  = 1;
  }
})

CodePudding user response:

Here a recursive solution with reduce(), which also works for deeper nested arrays if you need that.

function foo(array){
    let arrCounter=0;
    return array.reduce((acc,curr)=>{
        if(!Array.isArray(curr)) acc[curr]=curr
        else{ arrCounter =1;
            acc[`array${arrCounter}`]=foo(curr)        
        }
        return acc;
    },{})
} 

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];
console.log(foo(arr));

const deepArr =  [10,20,[40,50,60],70,80,[90,100,[40,50,60]],111,112];
console.log(foo(deepArr));

  •  Tags:  
  • Related