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.