How do I split the keys in an object into child objects?

  • 0
    Object given

    {
        "hero.a": "1",
        "hero.b": "1",
        "hero.c": "",
        "hero.d": "",
        "tools.a": "0",
        "tools.b": "0",
        "tools.c": "0",
    }


    Need to bring it to mind.

    {
        hero {
                 a: 1,
                 b:1,
                 c: '',
                 d:''       
    },
       tools{
              a: 0,
              b: 0,
              c: 0
              }
    }


    The only thought comes to it to re-create the object and add new values ‚Äč‚Äčthere through Object.keys. But is there a more elegant way?
    JavaScript Anonymous, Jun 11, 2019

  • 1 Answers
  • 0
    const data = {
    "hero.a": "1","hero.b": "1","hero.c": "","hero.d": "","tools.a": "0","tools.b": "0","tools.c": "0",
    };

    for (item in data) {
    const elems = item.split(".");
    data[elems[0]] = { ...data[elems[0]], [elems[1]]: data[item] };
    delete data[item];
    }

    console.log(data);
    Julia Hunter

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!