如何从键字符串创建嵌套的 JSON 结构?

huangapple go评论68阅读模式
英文:

How to form a nested json structure from keys string?

问题

{
    global: {
        fontsize: {
            bodyscale: {
                value: currValue
            }
        }
    }
}
英文:

I have two variables: currValue and keys, which is a string of keys separated by . like this: global.fontsize.bodyscale. I want to create a nested json structure from this string. The json structure should like:

{
    global: {
        fontsize: {
            bodyscale: {
                value: currValue
            }
        }
    }
}

How can I do this?

答案1

得分: 4

你可以使用 reduceRight 来基于键重复地用父对象包裹初始对象。

const currValue = 'hello';
const keys = 'global.fontsize.bodyscale';

const result = keys.split('.')
  .reduceRight((obj, key) => ({[key]: obj}), {value: currValue})

console.log(result)
英文:

You can use reduceRight to repeatedly wrap the initial object with parent objects, based on the keys.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const currValue = &#39;hello&#39;;
const keys = &#39;global.fontsize.bodyscale&#39;;

const result = keys.split(&#39;.&#39;)

.reduceRight((obj, key) => ({[key]: obj}), {value: currValue})

console.log(result)

<!-- end snippet -->

答案2

得分: 0

const keys = 'global.fontsize.bodyscale'
const currValue = 123

const keysList = keys.split('.')

const result = {}

let current = result
for (const key of keysList.slice(0, -1)) {
  current[key] = {}
  current = current[key]
}
current[keysList.at(-1)] = currValue

console.log(result)
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const keys = &#39;global.fontsize.bodyscale&#39;
const currValue = 123

const keysList = keys.split(&#39;.&#39;)

const result = {}

let current = result
for (const key of keysList.slice(0, -1)) {
  current[key] = {}
  current = current[key]
}
current[keysList.at(-1)] = currValue

console.log(result)

<!-- end snippet -->

答案3

得分: 0

let keys = "global.fontsize.bodyscale";
const nested_keys = keys.split(".").reverse();
let obj = "currValue"

nested_keys.forEach((key) => {
    result = {}
    result[key] = obj
    obj = result
})

console.log(obj)
英文:

You can use following code for this

let keys = &quot;global.fontsize.bodyscale&quot;;
const nested_keys = keys.split(&quot;.&quot;).reverse();
let obj = &quot;currValue&quot;

nested_keys.forEach((key) =&gt; {
    result = {}
    result[key] = obj
    obj = result
})

console.log(obj)

huangapple
  • 本文由 发表于 2023年6月21日 23:47:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定