I'm trying to iterate through a JSON schema object which have many nested properties.
{
"schema": {
"type: "object",
"properties": {
"nestObj1": {
"type: "object",
"properties": {
"nestObj12": {
"type":string
"nestObj2": {
"type": "object",
"properties": {
"nestObj22": {
"type": "object",
"properties": {
"nestObj23": {
"type": "string"
}
}
I want to turn the above into this
{
"nestObj1": {
"nestObj12": ""
},
"nestObj2": {
"nestObj22": {
"nestObj23": ""
}
}
}
I feel like recursion would be best to do this, but I just can't think of how to recursively go through the entire thing and creating key value as we go along. nestObj will stop when the type is a string and will continue if it is an object type.
To do what you are wanting recursion is definitely a good way to do. Heres an example that would work with what you have provided
function generateDataFromSchema(schema) { if (!schema) { return } if (schema.type === 'string') { return '' } const parsedData = {} Object.keys(schema.properties).forEach( (item) => { parsedData[item] = generateDataFromSchema(schema.properties[item]) }) return parsedData } const dataToParse = { schema: { type: 'object', properties: { nestObj1: { type: 'object', properties: { nestObj12: { type: 'string' } } }, nestObj2: { type: 'object', properties: { nestObj22: { type: 'object', properties: { nestObj23: { type: 'string' } } } } } } } }; console.log(generateDataFromSchema(dataToParse.schema))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.