gpt4 book ai didi

javascript - 将javascript点符号对象转换为嵌套对象

转载 作者:可可西里 更新时间:2023-11-01 01:45:57 25 4
gpt4 key购买 nike

我正在尝试构建一个可以扩展对象的函数,例如:

{
'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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com