Home > front end >  convert array to object in javascript (starting from 1 instead of 0)
convert array to object in javascript (starting from 1 instead of 0)

Time:11-19

How do i convert this:

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

to this:

{1:1,2:2,'array1':{4:4,5:5,6:6},7:7,8:8,'array2':{9:9,0:0},11:11,12:12}

I tried this:

Object.assign({}, input);

but the value of object index begins from 0 . I want it to start from 1. also how do i name the arrays within the arrays : like array 1 and array 2?

CodePudding user response:

You have two levels of array in your input so you can't just use Object.assign() like you did.

You should do it this way:

const input = [1,2,[4,5,6],7,8,[9,0],11,12]

const secondLevelArrToObj = input.map(elt => {
    let countingArr = 1 
    if (Array.isArray(elt)) {
        const obj = {}
        const arrNum = 'array'   countingArr
        obj[arrNum] = Object.assign({}, elt)
        countingArr  = 1
        return obj
    } else {
        return elt
    }
})

const output = Object.assign({}, secondLevelArrToObj)

console.log(output)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Regarding your question: You'll always have index starting from 0 in an object. JS works this way.

CodePudding user response:

You could build new objects and keep the count for nested arrays.

const
    convert = (array, count = { n: 1 }) => Object.fromEntries(array.map(v => Array.isArray(v)
        ? ['array'   count.n  , convert(v, count)]
        : [v, v]
    )),
    data = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12],
    result = convert(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use Array#reduce() as follows:

const input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
let arr = 0;
const output = input.reduce((obj, elm) => ({
    ...obj,
    [typeof elm === 'number' ? elm : `array${  arr}`]: typeof elm === 'number' ? elm : elm.reduce((acc, cur) => ({
        ...acc,
        [cur]: cur
    }), {})
}), {});

console.log(output);

DEMO

Show code snippet

const input = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
    let arr = 0;
    const output = input.reduce((obj, elm) => ({
        ...obj,
        [typeof elm === 'number' ? elm : `array${  arr}`]: typeof elm === 'number' ? elm : elm.reduce((acc, cur) => ({
            ...acc,
            [cur]: cur
        }), {})
    }), {});

    console.log(output);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related