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

标签 javascript

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

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

相关文章:

javascript - react map 不是一个功能

javascript - 绑定(bind)到文本突出显示

javascript - 为什么 `new Array()` 和 `Array()` 在 Javascript 中的行为相同?

javascript - 如何使用chart.js将数组添加到条形图?

javascript - 简单的 POST 请求在 Postman 中有效,但在浏览器中无效

javascript - 悬停时更改两个 id 的背景颜色?

javascript - 将 div block 插入另一个 div,在指定字符数之前

javascript - 第一个 XMLHttpRequest 失败但仅在 IE9 上

javascript - 当我的变量中有 '#' 时,为什么字符串不能正确传递到服务器?

javascript - 自定义 mobiscroll 中的动态内容