【问题标题】:How to convert string to object in object in js? [duplicate]如何在js中将字符串转换为对象中的对象? [复制]
【发布时间】:2021-05-21 11:32:14
【问题描述】:

我有一个字符串:'lorem,ipsum,dolor,sit,amet' 我想编写一个带有参数的函数,将作为参数传递的这个字符串转换为这样的对象:

{
     lorem:{
       ipsum:{
         dolor:{
           sit:{
             amet: []
           }
         }
       }
     }
 }

【问题讨论】:

标签: javascript json string object


【解决方案1】:

拆分字符串,使用Array.reduceRight()生成对象:

const fn = (str, param) =>
  str.split(',')
   .reduceRight((acc, key) => ({ [key]: acc }), param)

const str = 'lorem,ipsum,dolor,sit,amet'

const result = fn(str, [])

console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2014-07-19
    • 2013-07-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多