1
var seriesObj = {}
var result = [
    ['a','b'],
    [14, 5, 4, 11, 23, 5, 24, 6, 34, 53, 13, 2]
]
var seriesArr = []
var i
var resultLen = result[1].length
for (i = 0; i < resultLen; i++) {
    seriesObj.meta = 'Count'
    seriesObj.value = result[1][i]
    seriesArr.push(seriesObj)
    console.log(seriesArr)
}

https://jsfiddle.net/sgbxsbz5/2/

I can't understand why I am getting a different result than what I expect.

My expected final result is an Array holding Objects with corresponding different values but all I get is Objects in an Array with repeated same values...?

E.g.

0: Object
meta: "Count"
value: 2

1: Object
meta: "Count"
value: 2

But I expect

0: Object
meta: "Count"
value: 14

1: Object
meta: "Count"
value: 5

Why is that?

3 Answers 3

4

Because even though in JS variables are passed by value, the value of an object is a reference.

At each call of seriesArr.push(seriesObj), you are passing the same reference to seriesObj.

Instead, you should create a new object at each iteration:

seriesArr.push({
  meta: 'Count',
  value: result[1][i]
});
Sign up to request clarification or add additional context in comments.

Comments

1

You should be using map MDN for this

var seriesArr = result[1].map(function(val){
    return { meta: 'Count', value: val };
});

For the explanation of the why your version didn't work though...

When seriesObj is pushed to seriesArr, seriesArr gets a reference to the value of seriesObj. The value of the variable seriesObj is an object. The properties of that object may change, but the value of the variable seriesObj is still that object.

In order to push separate objects into the array, the value of the variable seriesObj needs to change to a different object.

This can be accomplished by simply creating a new object inside of the for loop.

 for (i = 0; i < resultLen; i++) {
     seriesObj = {};
     seriesObj.meta = 'Count'
     seriesObj.value = result[1][i]
     seriesArr.push(seriesObj)
     console.log(seriesArr)
 }

Comments

1

One way to fix this is to declare the object inside the for loop:

var result = [
['a','b'],
[14, 5, 4, 11, 23, 5, 24, 6, 34, 53, 13, 2]
]
var seriesArr = []
var i
var resultLen = result[1].length
for (i = 0; i < resultLen; i++) {
var seriesObj = {}
seriesObj.meta = 'Count'
seriesObj.value = result[1][i]
seriesArr.push(seriesObj)
console.log(seriesArr)
}

Comments

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.