5

Use this function to flatten the response returned from strapi on version 4. Helps you get rid of data and attributes properties

This will give you the same response structure as version 3 of strapi. This would help you migrate to version 4 from version 3 easily.

How to use it?

  1. import the file.
  2. const flattnedData = flattenObj({...data})

NOTE: The data here is the response returned from strapi version 4.

export const flattenObj = (data) => {
const isObject = (data) =>
    Object.prototype.toString.call(data) === "[object Object]";
const isArray = (data) =>
    Object.prototype.toString.call(data) === "[object Array]";

const flatten = (data) => {
    if (!data.attributes) return data;

    return {
    id: data.id,
    ...data.attributes,
    };
};

if (isArray(data)) {
    return data.map((item) => flattenObj(item));
}

if (isObject(data)) {
    if (isArray(data.data)) {
    data = [...data.data];
    } else if (isObject(data.data)) {
    data = flatten({ ...data.data });
    } else if (data.data === null) {
    data = null;
    } else {
    data = flatten(data);
    }

    for (const key in data) {
       data[key] = flattenObj(data[key]);
    }

    return data;
}

return data;
};
4
  • Won’t that affect performance too much if you have a lot of data and requests coming in? I’m currently debating doing this on the backend vs. on the frontend. Commented Mar 17, 2022 at 22:11
  • 1
    I have used this with a lot of data and I don't see any effect on the performance as of now. I'm currently using this on the frontend and everything work flawlessly Commented Mar 25, 2022 at 4:21
  • how did you handle query thing? Query in v4 is a bit complex(data, attributes etc) than v3... Thanks Commented Jun 20, 2022 at 5:07
  • I get the data back and it's stored in v3 format in the variable flattnedData . Place the above code in another file and import it ex: import { flattenObj } from './file-name'; Commented Jun 25, 2022 at 4:21

2 Answers 2

4

There is a plugin called strapi-plugin-transformer.

We can configure to remove "attribute" and "data" keys from the responded JSON and you can configure which APIs to transform as well.

You can check it out here on strapi.io: strapi-plugin-transformer

Sign up to request clarification or add additional context in comments.

1 Comment

Only works with the API though not GraphQL
2

In my case I created a new middleware "flatten-response.js" in "middlewares" folder.

function flattenArray(obj) {
  return obj.map(e => flatten(e));
}

function flattenData(obj) {
  return flatten(obj.data);
}

function flattenAttrs(obj) {
  let attrs = {};
  for (var key in obj.attributes) {
    attrs[key] = flatten(obj.attributes[key]);
  }
  return {
    id: obj.id,
    ...attrs
  };
}

function flatten(obj) {
  if(Array.isArray(obj)) {
    return flattenArray(obj);
  }
  if(obj && obj.data) {
    return flattenData(obj);
  }
  if(obj && obj.attributes) {
    return flattenAttrs(obj);
  }
  for (var k in obj) {
    if(typeof obj[k] == "object") {
      obj[k] = flatten(obj[k]);
    }
  }
  return obj;
}

async function respond(ctx, next) {
  await next();
  if (!ctx.url.startsWith('/api')) {
    return;
  }
  ctx.response.body = flatten(ctx.response.body.data)
}

module.exports = () => respond;

And I called it in "config/middlewares.js"

    module.exports = [
  /* ... Strapi middlewares */
  'global::flatten-response' // <- your middleware,
  'strapi::favicon',
  'strapi::public',
];

1 Comment

Thanks for this. I modified it and use it on client-side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.