我正在尝试构建一个可以扩展对象的函数,例如:
{
'ab.cd.e' : 'foo',
'ab.cd.f' : 'bar',
'ab.g' : 'foo2'
}
进入嵌套对象:
{ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}
像这个 php 函数:Set::expand()
当然不使用 eval。
最佳答案
我相信这就是您所追求的:
function deepen(obj) {
const result = {};
// For each object path (property key) in the object
for (const objectPath in obj) {
// Split path into component parts
const parts = objectPath.split('.');
// Create sub-objects along path as needed
let target = result;
while (parts.length > 1) {
const part = parts.shift();
target = target[part] = target[part] || {};
}
// Set value at end of path
target[parts[0]] = obj[objectPath]
}
return result;
}
// For example ...
console.log(deepen({
'ab.cd.e': 'foo',
'ab.cd.f': 'bar',
'ab.g': 'foo2'
}));
关于javascript - 将javascript点符号对象转换为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793811/