I want to flatten an object like this...
var obj1 = {
firstName: 'John',
lastName: 'Green',
car: {
make: 'Honda',
model: 'Civic',
revisions: [
{ miles: 10150, code: 'REV01', changes: },
{ miles: 20021, code: 'REV02', changes: [
{ type: 'asthetic', desc: 'Left tire cap' },
{ type: 'mechanic', desc: 'Engine pressure regulator' }
] }
]
},
visits: [
{ date: '2015-01-01', dealer: 'DEAL-001' },
{ date: '2015-03-01', dealer: 'DEAL-002' }
]
};
... into a daisy chain form like the following:
{
"firstName": "John",
"lastName": "Green",
"car.make": "Honda",
"car.model": "Civic",
"car.revisions.0.miles": 10150,
"car.revisions.0.code": "REV01",
"car.revisions.0.changes": ,
"car.revisions.1.miles": 20021,
"car.revisions.1.code": "REV02",
"car.revisions.1.changes.0.type": "asthetic",
"car.revisions.1.changes.0.desc": "Left tire cap",
"car.revisions.1.changes.1.type": "mechanic",
"car.revisions.1.changes.1.desc": "Engine pressure regulator",
"visits.0.date": "2015-01-01",
"visits.0.dealer": "DEAL-001",
"visits.1.date": "2015-03-01",
"visits.1.dealer": "DEAL-002"
}
Here's my (failed) attempt:
function flatten(obj) {
var flattenObject = {};
// iterate given object
for (let x in obj) {
if (typeof obj[x] == 'string') {
flattenObject[x] = obj[x];
}
if (typeof obj[x] == 'object') {
for (let y in obj[x]) {
flattenObject[x + '.' + y] = obj[x][y];
}
}
}
return flattenObject;
}
I quickly started repeating code unnecessarily in order to daisy chain inner objects and arrays. This is definitely something that needs recursion. Any ideas?
EDIT: This question is similar to other questions but not a duplicate. This question requires a specific notation and nested objects and arrays at the same time.
EDIT: I've also asked the opposite, unflatten, in another question.
Here's my code (typesciprt)
export const flatten = (data: object, prefix: string = '') => {
const result: { [key: string]: string | number | null } = {};
Object.entries(data).forEach(([key, value]) => {
if (typeof value === 'object') {
Object.assign(result, flatten(value, `${prefix}${key}.`));
} else {
result[`${prefix}${key}`] = value;
}
});
return result;
};
javascript version
export const flatten = (data, prefix = '') => {
const result = {};
Object.entries(data).forEach(([key, value]) => {
if (typeof value === 'object') {
Object.assign(result, flatten(value, `${prefix}${key}.`));
} else {
result[`${prefix}${key}`] = value;
}
});
return result;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With