Reputation: 9270
I'm attempting to fill an array with objects where the objects are all the same, and the keys are determined from a predefined item. I know I can do this with multiple if...else, but that seems to be a long method to use and was hoping for something more condensed and/or efficient without using external libraries.
Current method to fill array with hardcoded Objects:
fillArray(arr,n) {
while(arr.length < n) {
arr.push({
'x': Math.round(Math.random(),
'name': 'item' + arr.length + 1
});
}
}
Example of what I'd like to achieve using an if:
fillArray(arr, n, type) {
while(arr.length < n) {
if ( type === 'type1' ) {
arr.push({
'x': Math.round(Math.random(),
'name': 'item' + arr.length + 1
});
} else if ( type === 'type2') {
arr.push({
'x': Math.round(Math.random(),
'y': Math.round(Math.random(),
'name': 'item' + arr.length + 1
});
}
}
}
In my application I will use this type of method with a dozen if items, and there will be similar methods as well. I do not wish to apply any static typing for these items, since my application may require object keys to be dynamically added.
An idea I had that I can't seem to get a complete idea in my head would be somehow pre-defining an array of objects, and then using a find to somehow apply each item in the array as a type.
Psuedo-code (untested):
myTypes = [{
type: 'type1', keys: ['x', 'name']},
{type: 'type2', keys: ['x', 'y', 'name']
}];
fillArray(arr,n, type) {
let currentType = this.myTypes.find( myTypes => myTypes.type === type).keys
while(arr.length < n) {
// add for loop to iterate over each key/value here separately
}
}
Would this type of method work, be efficient, and is a reasonable practice to this approach? Are there any other standard practices for this type of array population with dynamic keys?
Upvotes: 1
Views: 151
Reputation: 222626
Moving to dynamic properties with object like keys
will harm type safety. Since TypeScript is a primary language, this is an important concern. Also, keys
doesn't allow to control property values.
It can be a hierarchy of classes or some factory functions:
class Type1 {
x = ...;
name = ...;
}
class Type2 extends Type1 {
y = ...;
}
const typesMap = { type1: Type1, type2: Type2 };
fillArray(arr, n, type) {
while(arr.length < n) {
arr.push(new typesMap[type])
}
}
The difference from the original code is that it won't work properly if type
is incorrect or missing, which may or may not be desirable.
Upvotes: 2