I have a JSON file that comes in a particular structure (see Tree), but I need it too be structured like expected output.
Is it possible to reorganise the data in JS? If so, how do you go about this? I need help in restructuring or mapping the tree to the expected output. I hope you guys can help me with this restructuring problem.
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: {}
}
},
]
CodePudding user response:
You could take an object for the various types and their functions to build the wanted structure for mapping children.
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; }
CodePudding user response:
- Parse your json data
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
- Map the data to fit your needs
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map
(or loop through it, whatever works for you)
CodePudding user response:
First, I'm a Miss, not Sir