Since this is a first found google result on “Strapi 4 simplify object”, let me share a simple GTD function which I use:
const simplifyStrapiObject = obj => {
if (obj.data && obj.data.attributes !== undefined) {
Object.assign(obj, obj.data.attributes);
obj.id = obj.data.id;
delete obj.data;
delete obj.meta;
}
if (obj.attributes) {
Object.assign(obj, obj.attributes);
delete obj.attributes;
}
const relationships = Object.keys(obj).filter(key => key !== 'data');
relationships.forEach(relationship => {
const children = obj[relationship];
if (Array.isArray(children?.data) && children.data?.length > 0) {
const mapped = children.data.map(child => simplifyStrapiObject(child))
obj[relationship] = mapped;
} else if (children?.data !== undefined) {
obj[relationship] = simplifyStrapiObject(children)
}
});
return obj;
}
Use like for any controller, such as super.create() - here for a entity called Payment:
const payment = await super.create(ctx);
simplifyStrapiObject(payment)
return payment;
Please note that this function deliberately removes meta and therefore pagination info. Our use is for quickly returning just-created data.