简体   繁体   English

如何将点表示法的字符串转换为具有值的嵌套 object?

[英]How do I turn a string in dot notation into a nested object with a value?

I was trying to do this with split and reduce but I can't figure it out.我试图通过拆分和减少来做到这一点,但我无法弄清楚。

Here is my string and value这是我的字符串和值

const str = "stack.overflow.is.cool"
const value = "Indeed"

I would like to turn this into我想把它变成

{ stack: 
  { overflow: 
    { is: 
      { cool: indeed }
    }
  }
}

With map.与 map。 Also possible with reduce and recursive function..也可以使用减少和递归 function..

 const str = "stack.overflow.is.cool" const value = "Indeed" let obj = {}; let pointer = obj; str.split('.').map( (key, index, arr) => { pointer = (pointer[key] = (index == arr.length - 1? value: {})) }); console.log(JSON.stringify(obj, null, ' '));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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