DEV Community

Sai Kaustubh
Sai Kaustubh

Posted on • Edited on

Strapi v4 flatten complex response structure.

As we know that the strapi version 4 returns a very complex response structure. With nested data and attributes properties. This gets very confusing and tough to manage if your working with a large set of collections.
The repetitive response structure of the version 4, bugged me out to constantly add the data and the attributes property. So this is a function which flattens the response structure and helps you work with the version 3 of strapi without much workover.


How to use it?
1) import the function file.
2) const flattenData = flattenObj({...data});

NOTE: The data in step 2 is the data that is return from the response of strapi.


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;
    };
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
causticrez profile image
Andrés Carvajal

Thanks Man!