英文:
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 = 'hello';
const keys = 'global.fontsize.bodyscale';
const result = keys.split('.')
.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 = '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)
<!-- 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 = "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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论