skip to Main Content

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?

3

Answers


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

    const currValue = 'hello';
    const keys = 'global.fontsize.bodyscale';
    
    const result = keys.split('.')
      .reduceRight((obj, key) => ({[key]: obj}), {value: currValue})
    
    console.log(result)
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
  3. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search