Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
nested array to object javascript

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!