Tengo un archivo JSON que viene en una estructura particular (ver Árbol), pero también necesito que esté estructurado como el resultado esperado.
¿Es posible reorganizar los datos en JS? Si es así, ¿cómo haces esto? Necesito ayuda para reestructurar o asignar el árbol al resultado esperado. Espero que me puedan ayudar con este problema de reestructuración.
const tree = [ { "type": "object", "name": "pets", "child": [ { type: "array", name: "properties", "child": [ { type: "object", name: "PK", }, { type: "object", name: "PO", }, { type: "object", name: "PS", }, { type: "object", name: "PA", child: [{type: "array", name: "list"}, ] }, ] }, { type: "object", name: "get", } ] }, ] const expectedResult = [ { pets: { properties: [ { name: "PK" }, { name: "PO" }, { name: "PS" }, { "PA" : { list: [] } } ], get: {} } }, ]Puede tomar un objeto para los distintos tipos y sus funciones para construir la estructura deseada para mapear niños.
const tree = [{ type: "object", name: "pets", child: [{ type: "array", name: "properties", child: [{ type: "object", name: "PK" }, { type: "object", name: "PO" }, { type: "object", name: "PS" }, { type: "object", name: "PA", child: [{ type: "array", name: "list" }] }] }, { type: "object", name: "get" }] }], types = { object: (name, child) => child ? { [name]: Object.assign({}, ...child.map(fn)) } : { name: name }, array: (name, child = []) => ({ [name]: child.map(fn) }) }, fn = ({ type, name, child }) => types[type](name, child), result = tree.map(fn); console.log(result) .as-console-wrapper { max-height: 100% !important; top: 0; }https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map
(o recorrerlo, lo que funcione para usted)
Primero, soy una señorita, no un señor 😝
Bueno, aquí hay un ejemplo detallado, estas no son las mejores prácticas, pero creo que es la forma más fácil de entender.
// First create an empty array to store your results. let expectedResults = []; // Loop through you tree object for (let i in tree) { // create empty object for each tree object let treeObj = {}; // get the name of the object const objName = tree[i]['name']; // assign it as a key and set it's value as object treeObj[objName] = {}; // get the children const objChild = tree[i]['child']; // loop through the children for (let j in objChild) { // get the name const childName = objChild[j].name; // check the type and assign either as object either as array if (objChild[j].type === 'object') { treeObj[objName][childName] = {}; } if (objChild[j].type === 'array') { treeObj[objName][childName] = []; const childArr = objChild[j].child; for (let k in childArr) { if (childArr[k].type === 'object') { treeObj[objName][childName].push({ name: childArr[k].name }); } if (childArr[k].type === 'array') { // and so on } } } } expectedResults.push(treeObj); }