JavaScript >> Javascript 文檔 >  >> Tags >> object

在 JavaScript 中遞歸地將對象轉換為數組

Object.entries() JavaScript 中的方法可用於將對象轉換為數組——但它不能遞歸工作。所以這裡有一個函數來完成它。

我想不出一個原因為什麼 你想這樣做,但它是在整理一篇關於使用 Object.entries() 的文章時提出的 ——就是這樣!

將對象轉換為數組的遞歸函數

我會讓評論來討論正在發生的事情。 它的要點是(無論出於何種原因)您想要將一個對像以及其中的任何對象轉換為數組/鍵對值作為 Object.entries() 的輸出 .數組本身將保持原樣。

//Demonstration object - a mess of nested objects and arrays
var myObject = {
    colour: 'blue',
    number: 43,
    name: 'Fred',
    enabled: true,
    subArray: [0, 1, {
        height: 60
    }],
    subObject: {
        foo: 'bar',
        anotherSubObject: {
            deep: 'dive',
            mood: {
                happy: false
            }
        }
    }
};

//Function to convert objects containing nested objects and arrays to array pairs similar to Object.entries()
function propertiesToArray(val) {

    //By default (val is not object or array, return the original value)
    var result = val;

    // If object passed the result is the return value of Object.entries()
    if (typeof val === 'object' && !Array.isArray(val)) {
        result = Object.entries(val);
        // If one of the results is an array or object, run this function on them again recursively
        result.forEach((attr) => {
            attr[1] = propertiesToArray(attr[1]);
        });
    }

    //If array passed, run this function on each value in it recursively
    else if (Array.isArray(val)) {
        val.forEach((v, i, a) => {
            a[i] = propertiesToArray(v)
        });
    }

    // Return the result
    return result;
}

// Test the function
console.log(propertiesToArray(myObject));


Tutorial JavaScript 教程
  1. 什麼是 React 以及為什麼要使用它?

  2. 微信還不夠

  3. 使用 TypeScript 中的可選鏈結交朋友

  4. CSS3 過渡完成時的回調

  5. 我最喜歡的一些數組方法

  6. 嘗試安全函數調用

  7. 使用 React Native 的聊天應用程序(第 4 部分):使用 react-native-gifted-chat 創建聊天 UI 屏幕的指南

  1. Angulars 路由器:簡介

  2. 在不支付取消費用的情況下取消 Adob​​e

  3. TypeScript 簡介

  4. 通過 POST 傳遞時如何在文本區域中保留換行符?

  5. Discord.js 錯誤 – MaxListenersExceededWarning:檢測到可能的 EventEmitter 內存洩漏

  6. 為什麼 JavaScript 的 parseInt 的基數默認為 8?

  7. 構建一個簡單的 Vue 3 應用程序並享受天文學! (第 1 部分,共 3 部分)

  1. 🎉 僅介紹格式 |格式化代碼的最快方法!

  2. 將 testing-playground 與 React 測試庫一起使用

  3. 現實世界中的可選鏈接(React 視頻聊天應用程序)

  4. tsParticles 1.39.3 發布