How To Flatten A Javascript Object Into A Daisy Chain Like Form?
I want to flatten an object like this... var obj1 = { firstName: 'John', lastName: 'Green', car: { make: 'Honda', model: 'Civic', revisions: [ { miles: 1015
Solution 1:
You can create recursive function like this, and its important to store previous keys in one string.
var obj1 = {
firstName: 'John',
lastName: 'Green',
car: {
make: 'Honda',
model: 'Civic',
revisions: [
{ miles: 10150, code: 'REV01', changes: 0},
{ 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' }
]
};
functionflatten(data, c) {
var result = {}
for(var i in data) {
if(typeof data[i] == 'object') Object.assign(result, flatten(data[i], c + '.' + i))
else result[(c + '.' + i).replace(/^\./, "")] = data[i]
}
return result
}
console.log(JSON.stringify(flatten(obj1, ''), 0, 4))
Solution 2:
try this:
functionflatten(obj)
{
var result = {};
(functionf(e, p) {
switch (typeof e) {
case"object":
p = p ? p + "." : "";
for (var i in e)
f(e[i], p + i);
break;
default:
result[p] = e;
break;
}
})(obj);
return result;
}
var obj1 = {
firstName: 'John',
lastName: 'Green',
car: {
make: 'Honda',
model: 'Civic',
revisions: [{
miles: 10150,
code: 'REV01',
}, {
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'
}]
};
console.log(flatten(obj1));
Solution 3:
Here's my code (typesciprt)
exportconstflatten = (data: object, prefix: string = '') => {
constresult: { [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
exportconstflatten = (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;
};
Post a Comment for "How To Flatten A Javascript Object Into A Daisy Chain Like Form?"