I have this simple nested object which I need to flatten to be able to insert it into my database.
const input = {
name: "Benny",
department: {
section: "Technical",
branch: {
timezone: "UTC",
},
},
company: [
{
name: "SAP",
customers: ["Ford-1", "Nestle-1"],
},
{
name: "SAP",
customers: ["Ford-2", "Nestle-2"],
},
],
};
The desired result is like this, each value in the arrays results in a new sub-object stored in an array:
[
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Ford-1",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Nestle-1",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Ford-2",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Nestle-2",
},
]
Instead of the result below which all fields stored in single object with indexes:
{
name: 'Benny',
'department.section': 'Technical',
'department.branch.timezone': 'UTC',
'company.0.name': 'SAP',
'company.0.customers.0': 'Ford-1',
'company.0.customers.1': 'Nestle-1',
'company.1.name': 'SAP',
'company.1.customers.0': 'Ford-2',
'company.1.customers.1': 'Nestle-2'
}
My code looks like this:
function flatten(obj) {
let keys = {};
for (let i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == "object") {
let flatObj = flatten(obj[i]);
for (let j in flatObj) {
if (!flatObj.hasOwnProperty(j)) continue;
keys[i + "." + j] = flatObj[j];
}
} else {
keys[i] = obj[i];
}
}
return keys;
}
Thanks in advance!
3
Answers
Edit
In the code below, I left your
flatten
functionality the same. I added afix
method that converts your original output into your desired output.Note: I changed the
name
value of secondcompany
toFOO
.Original response
The closest (legitimate) I could get to your desired result is:
I had to create a wrapper function called
flattenBy
that handles mapping the data by a particular key e.g.company
and passes it down to yourflatten
function (along with the current index).You could take the array’s values as part of a cartesian product and get finally flat objects.
This code locates all forks (places where arrays are located which indicate multiple possible versions of the input), and constructs a tree of permutations of the input for each fork. Finally, it runs all permutations through a flattener to get the desired dot-delimited result.
Note:
h
is a value holder, whereh.s
is set to 1 as soon as the first fork is found. This acts like a kind of global variable across all invocations ofgetFork
on a particular initial object, and forces only one fork to be considered at a time when building up a tree of forks.