The Object.entries() metodu v JavaScriptu lze použít k převodu objektu na pole – ale nefunguje rekurzivně. Zde je funkce, jak toho dosáhnout.
Nenapadá mě důvod proč chtěli byste to udělat, ale objevilo se to při sestavování článku o použití Object.entries() – tak tady to je!
Rekurzivní funkce pro převod objektů na pole
O tom, co se děje, nechám mluvit komentáře. Podstatou je, že (z jakéhokoli důvodu) chcete převést objekt a jakékoli objekty v něm na hodnoty pole/klíčového páru jako výstup pomocí Object.entries() . Samotná pole budou ponechána tak, jak jsou.
//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));