If you need a universal method for populating any object with data from an array of values, here is how you can achieve it (provided that the properties in the class are declared in the same order as the data in the array):
class User {
firstName = '';
lastName = '';
userName = '';
email = '';
}
const data = [
["Adam", "Richardson", "AdMan", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3b297929eb3968b929e839f96dd909c9e">[email protected]</a>"],
["Ahmad", "Ali", "MarketMan", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88c9e0e5e9ecc8edf0e9e5f8e4eda6ebe7e5">[email protected]</a>"],
["Feng", "Trunk", "SuperMan", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2a4878c85a2879a838f928e87cc818d8f">[email protected]</a>"],
["Chris", "Garcia", "SmartMan", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="490d262728252d092c31282439252c672a2624">[email protected]</a>"]
];
function fromDataArray<T>(klass: new () => T, data: any[]) {
const obj = new klass();
Object.keys(obj).forEach((k, i) => obj[k] = data[i]);
return obj;
}
const users = data.map(d => fromDataArray(User, d));
When dealing with nested objects, one challenge is losing type information once TypeScript is transpiled to JavaScript. To address this issue, ensure that your classes have initial objects that instantiate properties meant to be objects with instances of their respective types.
The following example demonstrates handling nested object data arrays:
function fromDataArray<T>(klass: new () => T, data: any[]) {
const obj = new klass();
Object.keys(obj).forEach((index, value) => {
if (Array.isArray(obj[index])) {
if (obj[index].length && typeof obj[index][0] === "object") {
obj[index] = data[value].map(innerData => fromDataArray(obj[index][0].constructor, innerData));
}
else {
obj[index] = data[value];
}
}
else if (typeof obj[index] === "object") {
obj[index] = fromDataArray(obj[index].constructor, data[value])
}
else {
obj[index] = data[value];
}
});
return obj;
}
// Classes for nested objects
// Data array structure provided for demonstration
const crazyData = data.map(d => fromDataArray(Class1, d));
The output will be an array of objects formatted accordingly:
Note: This view presents JSON representation, but the data objects retain their specific types.
{
"firstName": "Adam",
"subClass1": {
"lastName": "Richardson",
"subClass2": {
"userName": "AdMan",
"stuffz": [
{
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c4d686d614c69746d617c6069226f6361">[email protected]</a>"
}
]
}
}
}