从带有带点的键的对象创建对象

时间:2021-03-29 10:12:42

标签: javascript typescript object

我有一个类似的输入:

{
survey.subObject1.key1: true,
survey.subObject1.key2: "OTHER",
survey.subObject2.key3: "[1,2]",
survey.subObject2.key4: false,
survey2.subObject3.key5: false,
survey2.subObject3.key6: false
}

我想把它转换成一个对象,比如:

{
  survey: {
    subObject1 : {
      key1: true,
      key2: "OTHER"
    },
    subObject2 : {
      key3: "[1,2]",
      key4: false
    }
  },
  survey2: {
    subObject3 : {
      key5: false,
      key6: false
    }
  }
}

现在,我可以将键串起来并有一个 for,但我不知道如何在之后重新创建对象:

const x = {
"survey.subObject1.key1": true,
"survey.subObject1.key2": "OTHER",
"survey.subObject2.key3": "[1,2]",
"survey.subObject2.key4": false,
"survey2.subObject3.key5": false,
"survey2.subObject3.key6": false
}

for (const [key, value] of Object.entries(x)) {
      console.log(key)
      console.log(value);
}

2 个答案:

答案 0 :(得分:1)

它不漂亮,但很管用!

基本上,在 reduce 上使用 Object.entries 并使用扩展 (...) 运算符累积对象。

const x = {
"survey.subObject1.key1": true,
"survey.subObject1.key2": "OTHER",
"survey.subObject2.key3": "[1,2]",
"survey.subObject2.key4": false,
"survey2.subObject3.key5": false,
"survey2.subObject3.key6": false
}

const result = Object.entries(x).reduce( (acc,entry) => {
   const [key1,key2,key3] = entry[0].split('.');
   return {
      ...acc, 
      [key1]: {
         ...acc[key1], 
         [key2]:{
            ...(acc[key1]?acc[key1][key2]:{}), 
            [key3]:entry[1]
         }
      }
   };
},{});

console.log(result);

答案 1 :(得分:0)

我提出的最佳解决方案是使用 https://www.npmjs.com/package/dot-object,然后您可以:

const x = {
"survey.subObject1.key1": true,
"survey.subObject1.key2": "OTHER",
"survey.subObject2.key3": "[1,2]",
"survey.subObject2.key4": false,
"survey2.subObject3.key5": false,
"survey2.subObject3.key6": false
}
//transform to an object 
const y = dot.object(x)

//get back to dot structure
const z = dot.dot(x)