I have a deeply nested javascript object, which can contain a properties field- which is an object where the key represent the property name and the values represent the rest of the property data. I want to transform the property object into an array of objects where the key is combined with the values. For example, this is what i have:
const test = {
properties: {
meta: {
type: 'object',
properties: {
agencyId: {
type: 'string',
example: 'e767c439-08bf-48fa-a03c-ac4a09eeee8f',
description: 'agencyId',
},
},
},
data: {
type: 'object',
properties: {
intervalStartTime: {
type: 'string',
description: 'Time in GMT',
example: '1591702200000',
},
group: {
type: 'object',
properties: {
groupType: {
type: 'string',
description: 'Group Type',
example: 'vip',
},
numberofRequests: {
type: 'number',
example: 10198,
description: 'Amount of requests coming from group',
},
},
},
},
},
},
}
And this is what i want:
const test = {
properties: [
{
name: 'meta',
type: 'object',
properties: [
[
{
type: 'string',
example: 'e767c439-08bf-48fa-a03c-ac4a09eeee8f',
description: 'agencyId',
name: 'agencyId',
},
],
],
},
{
name: 'data',
type: 'object',
properties: [
[
{
type: 'string',
description: 'Time in GMT',
example: '1591702200000',
name: 'intervalStartTime',
},
{
name: 'group',
type: 'object',
properties: [
{
name: 'groupType',
type: 'string',
description: 'Group Type',
example: 'vip',
},
{
name: 'numberOfRequests',
type: 'number',
example: 10198,
description: 'Amount of requests coming from group',
},
],
},
],
],
},
],
}
I have a helper function that converts the objects into the form that I want, but I am struggling with recursively modifying the nested properties. This is what I have. Any suggestions on how I can modify the entire object into the structure that I need?
const convertObj = (obj) => {
return Object.entries(obj).reduce((initialVal, [name, nestedProperty]) => {
initialVal.push({ ...nestedProperty, name })
return initialVal
}, [])
}
const getNestedProperties = (data) => {
for (const key in data) {
const keyDetails = data[key]
if (keyDetails.hasOwnProperty('properties')) {
const keyProperties = keyDetails['properties']
keyDetails['properties'] = []
keyDetails['properties'].push(convertObj(keyProperties))
getNestedProperties(keyProperties)
}
}
}