Home > Software design >  Creating a nested object from entries
Creating a nested object from entries

Time:12-04

Is there a way to generate a nested JavaScript Object from entries?

Object.fromEntries() doesn't quite do it since it doesn't do nested objects.

const entries = [['a.b', 'c'], ['a.d', 'e']]

// Object.fromEntries(entries) returns:
{
    'a.b': 'c',
    'a.d': 'e',
}

// whatIAmLookingFor(entries) returns:
{
    a: {
        b: 'c',
        d: 'e',
    }
}

CodePudding user response:

You could reduce the array entries and reduce the keys as well. Then assign the value to the final object with the last key.

const
    setValue = (object, [key, value]) => {
        const
            keys = key.split('.'),
            last = keys.pop();
        keys.reduce((o, k) => o[k] ??= {}, object)[last] = value;
        return object;
    },
    entries = [['a.b', 'c'], ['a.d', 'e']],
    result = entries.reduce(setValue, {});

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

CodePudding user response:

I think I found a way using lodash:

import set from 'lodash/set'

const result = {}
const entries = [['a.b', 'c'], ['a.d', 'e']]

entries.forEach((entry) => {
    const key = entry[0]
    const value = entry[1]
    set(result, key, value)
})
  • Related