Iterating nested object
This example shows how to flatten complex JavaScript object into rows and send required properties to the output.
Motivation
Suppose we have to process complex structure of users and their phones. However, subsequent connector is not able to process complex schema (e.g. SQL Connectors), so we have to transform complex data into particular rows.
Ouput schema
Column | Data type |
---|---|
Login | string |
PhoneNumber | string |
Statement
// create array with nested objects
let users = [
{
"ID": 1,
"Login": "Alice",
"Phones": [
{
"Type": "Mobile",
"Number": "+420721234567"
},
{
"Type": "Home",
"Number": "+420722345678"
}
]
},
{
"ID": 2,
"Login": "Bob",
"Phones": [
{
"Type": "Mobile",
"Number": "+420723456789"
}
]
}
];
// flat array for collecting result
let phones = [];
// outer iteration of users
users.forEach((user) => {
// log outer record
log.info(`Checking phones from ${user.Login}...`);
// inner itearation of user''s numbers
user.Phones.forEach((phone) => {
// log user''s phone number and type
log.info(`Found phone ${phone.Number} (${phone.Type})`);
// add found number to the resulting array
phones.push(
{
"Login" : user.Login,
"PhoneNumber" : phone.Number
})
});
});
return phones;
Result
Login | PhoneNumber |
---|---|
Alice | +420721234567 |
Alice | +420722345678 |
Bob | +420723456789 |