1

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 = [];
for(var i =0; i <3; i++){
    var Object = {};
    Object['newKey'] = 1;
    newArray.push(Object);
}

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.

5
  • Well, I see some problems/ways in which it could be improved... Commented Aug 1, 2011 at 1:29
  • @Jared Farrish: could you suggest me over this Commented Aug 1, 2011 at 1:31
  • Well, first of all, when you say {}, you're creating an object, so that step/line is superfluous. Commented Aug 1, 2011 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. Commented Aug 1, 2011 at 1:37
  • 1
    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. Commented Aug 1, 2011 at 1:53

2 Answers 2

1

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

var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
    newArray.push({newKey: 1});
}

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Example updated per comments:

var length = 3,
    newArray = [];

for ( var i=0; i<length; i++ ) {
    var tempObj = {};
    tempObj['newKey'] = 'SomeValue';
    newArray.push(tempObj);
}

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

2 Comments

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.
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.