从条目创建嵌套对象

Ant*_*ime 5 javascript serialization json object deserialization

有没有办法Object从条目生成嵌套的 JavaScript?

Object.fromEntries()并没有完全做到这一点,因为它不执行嵌套对象。

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',
    }
}
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

您可以减少数组entries并减少键。然后将值分配给具有最后一个键的最终对象。

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);
Run Code Online (Sandbox Code Playgroud)