在对象中转换JavaScript点字符串

时间:2018-01-04 17:46:47

标签: javascript

给定一个JS字符串:var s = "deep.deeper.deepest",如何将其转换为如下对象:deep: {deeper: {deepest: {}}}

2 个答案:

答案 0 :(得分:2)

 const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);

将字符串数组(将原始字符串拆分)减少为对象链。或者功能稍差:

 function dottedToObj(str){
  const root = {};
  var acc = root;
  for(const key of str.split(".")){
    acc = acc[key] = {};
  }
  return root;
}

答案 1 :(得分:1)

一个简单的循环应该适用于此,只需移动每个虚线属性,同时向下移动对象中的一个级别:



const s = "deep.deeper.deepest";

function convertToObject(str) {
  const result = {};
  
  let inner = result;
  for (const key of s.split(".")) {
    // Give the object a child with this key
    inner[key] = {};
  
    // Set the current object to that child.
    inner = inner[key]
  }
  
  // Return the original
  return result;
}

console.log(convertToObject(s))