patternjavascriptMinor
Fill an array of objects with some default object
Viewed 0 times
objectsarraywithdefaultsomeobjectfill
Problem
I have an array of objects. Whatever may be the size of this array, I need to ensure the size of the array as
Is there a better method of doing it?
n using a default object.function fillRemaining(arr, n) {
var defaultObject = {'id' : 0, 'name' : ''};
var temp = 0;
while(arr.length + temp < n ) {
var template = $.extend({}, defaultObject);
template.id = new Date().getTime();
arr.push(defaultObject);
temp++;
}
}Is there a better method of doing it?
Solution
I see a few ways this can be improved.
First, you are creating the
I would also say that there is not a big reason why you should have a
Second, you are using a
Lastly, the name
Here's what I would suggest:
First, you are creating the
template variable as a copy of the defaultObject, but then you are inserting defaultObject rather than template. I am going to assume this is a bug.I would also say that there is not a big reason why you should have a
defaultObject, then create and modify a copy to add. Just create objects on the fly.Second, you are using a
while loop, but constructing it like a for loop (loop variable, incremented every iteration). You actually don't even use the loop variable, so it can be removed completely. There is also a second potential bug where you are checking against arr.length + temp in your conditional, but arr.length increases every time you add an element to the array, so you are counting by 2's instead of by 1's.Lastly, the name
fillRemaining does not clearly describe what the function is supposed to do. Since it is padding onto the end of the array, perhaps padArrayWithDefault or something similar might be more descriptive.Here's what I would suggest:
function padArrayWithDefault(arr, n) {
while(arr.length < n) {
arr.push({
"id": new Date().getTime(),
"name": ""
});
}
}Code Snippets
function padArrayWithDefault(arr, n) {
while(arr.length < n) {
arr.push({
"id": new Date().getTime(),
"name": ""
});
}
}Context
StackExchange Code Review Q#71662, answer score: 2
Revisions (0)
No revisions yet.