简体   繁体   中英

Creating a nested object from entries

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',
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM