# 5.对对象进行展开赋值

a = {
  "a.b.c": 1,
  c: 2,
};
let getObj = { "a.b.c": 1, "a.d": 2, e: 3 };
function getObj(obj) {
  let newObj = {};
  function helper(keys, value, newObj) {
    const key = keys.shift();
    if (keys.length === 0) {
      newObj[key] = value;
    } else {
      if (!newObj[key]) {
        newObj[key] = {};
      }
      helper(keys, value, newObj[key]);
    }
  }
  for (let index in obj) {
    let currKeys = index.split(".");
    let value = obj[index];
    helper(currKeys, value, newObj);
    // let currObj = newObj;
    // while (currKeys.length) {
    // 	const key = currKeys.shift();
    // 	if (currKeys.length === 0) {
    // 		currObj[key] = value;
    // 	} else {
    // 		if (!currObj[key]) {
    // 			currObj[key] = {};
    // 		}
    // 	}
    // 	currObj = currObj[key];
    // }
  }
  console.log(newObj);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Last Updated: 6/3/2024, 1:08:34 AM