【问题标题】:Creating a nested object from entries从条目创建嵌套对象
【发布时间】:2022-01-10 01:44:24
【问题描述】:

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

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

【问题讨论】:

    标签: javascript json object serialization deserialization


    【解决方案1】:

    您可以减少数组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);

    【讨论】:

      【解决方案2】:

      我想我找到了一种使用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)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-16
        相关资源
        最近更新 更多