0

I need help regarding insertion of array elements as objects into another array in Javascript. I have the following code:

tableLength = 3;
nyCourt = [];
oldArr = [Buy, String, Question]
for (var t = 0; t < tableLength; t++) {
 nyCourt.push({});
 for (var i = 0; i < OldArr.length; i++) {
 nyCourt.Title = OldArr[i] ;
 }
};

The code isnt working, I want output in the following format

[{Title:Buy },
{Title: String},
{Title: Question}]

But the output I get is this:

[{Title:Question },
{Title: Question},
{Title: Question}]
STT LCU
4,3304 gold badges32 silver badges47 bronze badges
asked Oct 30, 2013 at 8:32
1
  • "But the output I get is this" I don't think so, not with that code. Commented Oct 30, 2013 at 8:34

3 Answers 3

1

This line:

nyCourt.Title = OldArr[i] 

writes to the Title property on the nyCourt object (which is an array object), repeatedly in the loop. The last assignment wins.

But given what you've said you want your output to be, your code is over-complex. You only need one loop:

var nyCourt = [];
var oldArr = [Buy, String, Question];
for (var i = 0; i < oldArr.length; i++) {
 nyCourt.push({Title: oldArr[i] });
}

Live Example (use Chrome or something else modern) | Source

Or as this is Node so we know we have map:

var oldArr = [Buy, String, Question];
var nyCourt = oldArr.map(function(entry) {
 return {Title: entry};
});

Live Example | Source

answered Oct 30, 2013 at 8:34
Sign up to request clarification or add additional context in comments.

3 Comments

@Rajat: That makes no sense, given the output you've said you want. Why do you want two loops?
Because that is an assignment :(
@Rajat: Due respect, I think you've misunderstood the assignment. You either need two loops and the result you're supposed to achieve isn't what you've listed, or the result you've listed is correct and you shouldn't use two loops.
1
//this give the output you want
 tableLength = 3;
 nyCourt = [];
 oldArr = ['Buy', 'String', 'Question'];
 for (var t = 0; t < oldArr.length; t++) {
 nyCourt.push({Title: oldArr[t]});
 };
 console.log(nyCourt);
answered Oct 30, 2013 at 8:41

Comments

0

place that push function inside the loop also change the code like this

for (var t = 0; t < tableLength; t++) { 
 for (var i = 0; i < OldArr.length; i++) {
 nyCourt.push({"Title": oldArr[t]});
 }
 };
answered Oct 30, 2013 at 8:50

1 Comment

Thanks Arviin for the help

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.