在 JavaScript 中扁平化 JSON 物件


假設我們有一個 JSON 物件,它可能包含任意級別的巢狀 -

const obj = {
   "one": 1,
   "two": {
      "three": 3
   },
   "four": {
      "five": 5,
      "six": {
         "seven": 7
      },
      "eight": 8
   },
   "nine": 9
};

我們需要編寫一個 JavaScript 函式,它採用一個這樣的巢狀 JSON 物件,並返回一個不包含巢狀並使用點符號將相應的值對映到鍵的新物件。

因此,對於上面的物件,輸出應該類似於這樣 -

const output = {
   'one': 1,
   'two.three': 3,
   'four.five': 5,
   'four.six.seven': 7,
   'four.eight': 8,
   'nine': 9
};

示例

程式碼如下 -

 Live Demo

const obj = {
   "one": 1,
   "two": {
      "three": 3
   },
   "four": {
      "five": 5,
      "six": {
         "seven": 7
      },
      "eight": 8
   },
   "nine": 9
};
const flattenJSON = (obj = {}, res = {}, extraKey = '') => {
   for(key in obj){
      if(typeof obj[key] !== 'object'){
         res[extraKey + key] = obj[key];
      }else{
         flattenJSON(obj[key], res, `${extraKey}${key}.`);
      };
   };
   return res;
};
console.log(flattenJSON(obj));

輸出

而控制檯中的輸出將為 -

{
   one: 1,
   'two.three': 3,
   'four.five': 5,
   'four.six.seven': 7,
   'four.eight': 8,
   nine: 9
}

更新於: 2021 年 2 月 22 日

12K+ 次瀏覽

開啟職業生涯 征程

完成該課程以獲得認證

開始學習
廣告