Wasi
1
System Information
- Strapi Version : V4:
- Windows 11:
- Data Base: SQL:
- Node Version: 20.4.0:
- NPM Version: 9.6.6:
I have just created a header single tyoe wish hade a Logo field and 4 text feild and when i am called it from api/header so its give the response as
{
"data": {
"id": 1,
"attributes": {
"createdAt": "2023-10-09T17:54:44.136Z",
"updatedAt": "2023-10-09T17:56:26.677Z",
"publishedAt": "2023-10-09T17:56:26.147Z"
}
},
"meta": {}
}
And Dear Strapi Team I Just Want Like In Node JS and Express JS We Only Get The Data We Want So Can you PLease Help Me How Can I Resolve This and
I dont want to use populate=deep or any other pluging or any like populate=*
Please Can Anyone Guid Me How Can I Get This Type OF Response Like:
{
List1: “Hello”,
List2: “World”
}
Above JSOn is an example Only
Wasi
3
Where To Paste That Code ?
Wasi
4
Not Resolved Yet Please Someone from Strapi Team Help here
BigJump
6
Create a file in the folder /middlewares called flatten-api-response.js
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;
}
}
module.exports = () => respond;
Then open up /config/middlewares.js and paste this in at the end.
{
resolve:'middlewares/flatten-api-response.js'
}
If you don’t want to do all of that then look at Transformer | Strapi Market which will do this for you!
2 Likes