I see a few ways this can be improved.
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": "" }); } }