将深层嵌套对象的结构修改为对象数组

时间:2020-08-29 11:46:50

标签: javascript arrays object recursion

我有一个深层嵌套的javascript对象,该对象可以包含一个properties字段-这是一个对象,其中键代表属性名称,而值代表其余的属性数据。我想将属性对象转换为键与值组合在一起的对象数组。 例如,这就是我所拥有的:

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',
              },
            },
          },
        },
      },
    },
  }

这就是我想要的:

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',
              },
            ],
          },
        ],
      ],
    },
  ],
}

我有一个辅助函数,可以将对象转换为所需的形式,但是我在递归地修改嵌套属性时很费力。这就是我所拥有的。关于如何将整个对象修改为所需结构的任何建议?

 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)
      }
    }
  }

2 个答案:

答案 0 :(得分:1)

如果对象具有properties键,则映射条目并创建一个对象数组,每个键分别为name和其余值。遍历对象,并检查每个属性是否都是对象。如果是,则递归调用该函数。 { ...o }部分创建输入的副本,以使其不会发生变异。

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",}}}}}}};

function convert({ ...o }) {
  for (const key in o) {
    if (typeof o[key] === 'object')
      o[key] = convert(o[key])
  }

  if (o.hasOwnProperty("properties"))
    o.properties = Object.entries(o.properties).map(([name, v]) => ({ name, ...v }))

  return o
}

console.log(convert(test))

答案 1 :(得分:0)

如果没有properties属性,只需返回对象的其余部分。如果这样做,则返回对象的其余部分以及一个properties数组属性,该数组属性是通过获取该属性中的每个名称-值条目并将其添加到调用结果中的属性name将其转换为对象而形成的transform上的value

代码非常简单:

const transform = ({properties, ...rest} = {}) =>
  properties 
    ? {
        ... rest, 
        properties: Object .entries (properties) .map (([name, val]) => ({
          name, 
          ... transform (val)
        }))
      }
    : {... rest}

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'}, oup: {type: 'object', properties: {grupType: {type: 'string', description: 'Group Type', example: 'vip'}, numberofRequests: { type: 'number', example: 10198, description: 'Amount of requests coming from group'}}}}}}}

console .log (transform (test))
.as-console-wrapper {max-height: 100% !important; top: 0}