JSFiddle - React, Tailwind, and code Playground
by Richard Hunter
JavaScript
function parseSchema(key, schema, array = [], required = [], path = '$') {
if (schema.type === 'object') {
let result = parseProperties(schema.properties, schema.required, path);
result = [...array, ...result];
return result;
} else if(schema.type === 'array') {
console.log('is array');
// we don't want to show array items in columnar data
} else {
// scalar type
let item = {
name: key,
type: schema.type,
required: required.includes(key),
path,
}
return [...array, item];
}
return array;
}
const parseProperties = (properties, required, path) => {
return Object.keys(properties)
.reduce((memo, key) => parseSchema(key, properties[key], memo, required, `${path}['${key}']`), []);
}
const parsed = parseSchema('', {
type: "object",
required: ['foo', 'bar'],
properties: {
"foo": {
"type": "number"
},
"bar": {
"type": "object",
"properties": {
"moo": {
"type": "object",
"properties": {
"zig": {
"type": "string"
}
}
}
}
}
}
});
alert(parsed.map(item => item.name));