Recursively serialise object

Viewed 83

I am consuming a data structure from Contentful, which looks like this:

{
  sys: {}
  fields: {
    type: 'page',
    children: [
      {
        sys: {}
        fields: {
          type: 'section',
          children: [
            ...andSoOn
          ]
        }
      }
    ]
  }
}

I want to recursively serialise the data with the following pattern:

const serialise = entry => entry.fields

Basically, I want to flatten out the fields nested object, and remove the sys object.

How can I do this recursively, for any number of nested children?

2 Answers

You didn't specify the exact desired output, but I guess this is what you're looking for:

const data = {
  sys: {},
  fields: {
    type: 'page',
    children: [
      {
        sys: {},
        fields: {
          type: 'section',
          children: [
          ]
        }
      }
    ]
  }
};

const flatten = ({ fields }) => ({ ...fields, children: fields.children.map(flatten) });

console.log(flatten(data));

const allInOne = []
function seeker (item) {
  const { fields: { type, children } } = item
  const obj = { fields: { type } }
  allInOne.push(obj)
  children.forEach(seeker)
}

seeker(nestedObj)

like this?

Related