Tratando de convertir una matriz de objetos en un objeto anidado. ¿Hay un buen método para esto? y ¿cómo lo hago dependiendo de la longitud de la matriz?
Funciona pero no es universal: https://codesandbox.io/s/thirsty-roentgen-3mdcjv?file=/src/App.js
Lo que tengo:
sorting: [ { "id": "HighestDegree", "options": [ "HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor" ] }, { "id": "gender", "options": [ "male", "female" ] } ]Lo que quiero:
value: { "Region": "Oklahoma", "HighestDegree": { "HighSchool": { "male": null, "female":null }, "Undergraduate":{ "male": null, "female":null } //and so on... } }El código a continuación funciona, pero está codificado para solo dos opciones diferentes. Quiero que pueda anidar la longitud de la matriz. Entonces, digamos que otro objeto era la edad, sería {"HighSchool":{male:{"<25":null,"25-35":null}}} etc.
function testSortingArray() { let sorting = [ { id: "HighestDegree", options: ["HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor"] }, { id: "gender", options: ["male", "female"] } ]; let GoalArray = {}; if (sorting.length > 0) { sorting[0].options.map((firstArray) => { let currObject = {}; sorting[1].options.map((secondOption) => { currObject[secondOption] = null; }); GoalArray[firstArray] = currObject; }); } return GoalArray; } console.log(testSortingArray());Puedes hacerlo con una función recursiva.
La siguiente función reduce cada matriz de options a un objeto, y luego continúa llenando ese objeto si quedan elementos rest de la matriz de sorting original.
const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({ ...a, [v]: rest.length ? fn(rest): null }), {}); const result = fn(sorting); Además del método reduce() , el código anterior utiliza la desestructuración de objetos y matrices y la sintaxis extendida .
Fragmento completo:
const sorting = [{ "id": "HighestDegree", "options": [ "HighSchool", "Undergraduate", "Bachelor", "Master", "Doctor" ] }, { "id": "gender", "options": [ "male", "female" ] }, { "id": "age", "options": [ "<25", "25-35" ] }]; const fn = ([{ options }, ...rest]) => options.reduce((a, v) => ({ ...a, [v]: rest.length ? fn(rest): null }), {}); const result = fn(sorting); console.log(result);