JavaScript 中解析字符串为对象的递归方法


我们要求编写一个 JavaScript 函数,该函数接受一个字符串数组并返回一个与字符串相对应的对象。

例如 −

如果该数组为 −

const arr = [
   "country.UK.level.1",
   "country.UK.level.2",
   "country.US.level.1",
   "country.UK.level.3"
];

则输出应为 −

const output = {
   "country": [
       {"UK" : {"level" : ["1", "2", "3"]}},
       {"US" : {"level" : ["1","2"]}}
  ]
}

 

条件

存储在 str 数组中的字符串不会被排序,并且该代码应对此保持鲁棒性。

字符串将遵循 x.y.x.y... 模式,其中 x 将对该数组是唯一的,而 y 可以改变。在我的示例中,country 和 level 始终相同,因为它们表示 x 坐标。

这需要递归方法,因为存储在 str 数组中的字符串的长度可以任意。字符串越长,嵌套的深度就越大。

示例

代码如下 −

const arr = [
   "country.UK.level.1",
   "country.UK.level.2",
   "country.US.level.1",
   "country.UK.level.3"
];
const stringToObject = arr => {
   const obj = {};
   arr.forEach(str => {
      let curr = obj;
      let splitted = str.split('.');
      let last = splitted.pop();
      let beforeLast = splitted.pop();
      splitted.forEach( sub => {
         if(!curr.hasOwnProperty(sub)){
            curr[sub] = {};
         };
         curr = curr[sub];
      });
      if(!curr[beforeLast]){
         curr[beforeLast] = [];
      };
      curr[beforeLast].push(last);
   });
   return obj;
};
console.log(JSON.stringify(stringToObject(arr), undefined, 4));

输出

这会在控制台中产生以下输出 −

{
   "country": {
       "UK": {
           "level": [
               "1",
               "2",
               "3"
           ]
       },
       "US": {
           "level": [
               "1"
           ]
       }
   }
}

更新时间: 2020 年 10 月 1 日

412 次浏览

启动你的事业

通过完成课程获得认证

开始
广告
© . All rights reserved.