给定一个“扁平”字典对象,其键是点分隔的。
例如,{ ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}.
实现一个函数,将其转换为“嵌套”字典对象。
在上面的例子中,嵌套的版本如下:
{
‘A’: 1,
‘B’: {
‘A’: 2,
‘B’: 3
},
‘CC’: {
‘D’: {
‘E’: 4,
‘F’: 5
}
}
}
可以保证字典中没有键是其他键的前缀。
wo mei kan dong ti,ni keyi zai shuoyici ma?
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
不会写,调包吧!!!
<script>
let obj = { 'A': 1, 'B.A': 2, 'B.B': 3, 'CC.D.E': 4, 'CC.D.F': 5 };
let copyObj = {};
Object.keys(obj).forEach(key => {
Object.keys(obj).forEach(key => {
const keyMap = key.includes('.') ? key.split('.') : null;
if (!keyMap) copyObj[key] = obj[key];
if (keyMap) {
let idArr = [];
keyMap.forEach((item, index) => {
if (index === 0) {
idArr.push(item);
if (copyObj[item]) {
return;
}
Object.defineProperty(copyObj, item, { value: {}, writable: true, enumerable: true, configurable: true })
return;
}
if (index === keyMap.length - 1) {
let newObj = {};
idArr.forEach((item, index) => {
if (index === 0) {
newObj[index] = copyObj[item];
} else {
newObj[index] = newObj[index - 1][item];
}
})
Object.defineProperty(newObj[idArr.length - 1], item, { value: obj[key], writable: true, enumerable: true, configurable: true })
} else {
let newObj = {};
idArr.forEach((item, index) => {
if (index === 0) {
newObj[index] = copyObj[item]
} else {
newObj[index] = newObj[index - 1][item];
}
})
if (newObj[idArr.length - 1][item]) {
idArr.push(item);
return
}
Object.defineProperty(newObj[idArr.length - 1], item, { value: {}, writable: true, enumerable: true, configurable: true })
idArr.push(item);
}
})
}
})
})
console.log(copyObj);
</script>