Take the 2-minute tour ×

I have the length of my previous object and i need to create a new array of objects based on the length with new key's.

Length = 3;

var newArray = [];
    var Object = {};
    Object['newKey'] = 1;

This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].

Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.

share|improve this question
Well, I see some problems/ways in which it could be improved... –  Jared Farrish Aug 1 '11 at 1:29
@Jared Farrish: could you suggest me over this –  John Cooper Aug 1 '11 at 1:31
Well, first of all, when you say {}, you're creating an object, so that step/line is superfluous. –  Jared Farrish Aug 1 '11 at 1:32
And don't use Capitalized var names. "Object" is a class (in fact the base class of everything in JavaScript), so it's not a good idea to suddenly redeclare it to be... well, an instance of itself. (Length doesn't conflict with anything, but still - "length" is preferred.) In javascript, variables should be camelCase. –  Flambino Aug 1 '11 at 1:37
Can you explain a little better what you're trying to accomplish here? As in why you're doing this? There might be a better way to go about what you're doing. –  ReX357 Aug 1 '11 at 1:53
add comment

2 Answers

up vote 1 down vote accepted

Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)

var length = 3;
var newArray = [];
    newArray.push({newKey: 1});

but to be honest it's unclear to me exactly what you're trying to accomplish

share|improve this answer
add comment

You could make it slightly more dynamic by referencing the variable for length.

Example updated per comments:

var length = 3,
    newArray = [];

    var tempObj = {};
    tempObj['newKey'] = 'SomeValue';

I didn't really do more than clean up what you have.

share|improve this answer
Objects are passed by reference, so this will put the same object in each index of the array. I don't think this is what the OP wants. You should put tempObj = {}; inside the loop. –  mVChr Aug 1 '11 at 1:44
Won't work right. You're only creating 1 object, and then referencing that object multiple times in the array (edit: mVChr beat me to it) –  Flambino Aug 1 '11 at 1:44
add comment

Your Answer


