1

I am trying to take an array of numbers and make it into an array of objects. Here is what I have so far and I am not sure why it isn't working. (This is javaScript)

var objectArray = function (n, array){
    var multProblem = {Problem: "" ,Answer: 0};
    var newArray = [];
    for(var count = 0; count < array.length ; count++){
        multProblem.problem = "" + n + " x " + count;
        multProblem.answer = array[count];
        //console.log(multProblem);
        newArray.push(multProblem);
     }
     return newArray;
}

When I use console.log it shows what I want it to show, but when I try to push it to an array it winds up having every single object being Problem: 2x10 Answer: 20. If anyone can help it would be greatly appreciated.

2 Answers2

0

Move var multProblem = {};, inside the loop, that way for every item in the array, you can have a unique object.

var objectArray = function (n, array){  
var newArray = [];
for(var count = 0; count < array.length ; count++){
    var multProblem = {};
    multProblem.problem = "" + n + " x " + count;
    multProblem.answer = array[count];
    //console.log(multProblem);
    newArray.push(multProblem);
 }
 return newArray;
}
BatScream
  • 19,260
  • 4
  • 52
  • 68
0

Why so much complication when it's enough:

newArray.push({Problem: "" + n + " x " + count ,Answer: array[count]});

The whole thing:

var objectArray = function (n, array){
    var newArray = [];
    for(var count = 0; count < array.length ; count++){
        newArray.push({Problem: "" + n + " x " + count, Answer: array[count]});
     }
     return newArray;
}