'Flat certain properties in a Javascript object
Have a response from a data base with the next format
{
"data": [
{
"id": 1,
"attributes": {
"active": true,
"details": "TEST",
"client": {
"data": {
"id": 1,
"attributes": {
"code": "20000",
"technology": {
"data": {
"id": 2,
"attributes": {
"name": "TEST"
}
}
}
}
}
}
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 2
}
}
}
Each population from a relationship has a data propertie, within, it has an id and other propertie called attributes where the actual data is hold. Thing is, handling this from the frontend is a mess because you have to access two keys extra per level of relationship "data" and "attributes" so if you want to access a name of a neighborhood of a city, the call its like
city.data.attributes.neighborhood.data.attributes.name
I want to get rid of the data and attributes keys and simplify the object like this
{
"active": true,
"details": "TEST",
"client": {
"id": 1,
"code": "20000",
"technology": {
"id": 2,
"name": "TEST"
}
}
}
which is the same but without the data and attributes keys. I have to do this recusively because i can't know how much levels is gonna need.
I have this code but i think i'm far from a correct answer to this problem
function flatten (obj) {
const flattened = {}
Object.keys(obj).forEach((key) => {
const value = obj[key]
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
if (key === 'attributes') {
Object.assign(flattened, flatten(value))
} else {
flattened[parent] = flatten(value, key)
}
} else if (Array.isArray(value) && key === 'data') {
value.forEach((item) => {
Object.assign(flattened, flatten(item))
})
} else {
flattened[key] = value
}
})
return flattened
}
the response code is from Strapi headless CMS version 4.0.6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
