user1050619 user1050619 - 2 months ago 7
Javascript Question

Javascript key not populated in Object

I'm trying to create a object with keys/values but when I see the object, the keys are not populated correctly..

I expect the keys to be - 0,1,2,3 but it shows "index" as the key.

> categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"]
["09/07/2016 00:00", "09/07/2016 00:01", "09/07/2016 00:02", "09/07/2016 00:03", "09/07/2016 00:04"]

> rate_1 = [0.41,0.54,0.6,0.7,0.8]
[0.41, 0.54, 0.6, 0.7, 0.8]

> dict = []
[]

> categories.forEach(function(ix,index){console.log(index)
dict.push({index:rate_1[index]})
})
0
1
2
3
4

> JSON.stringify(dict)
"[{"index":0.41},{"index":0.54},{"index":0.6},{"index":0.7},{"index":0.8}]"

Answer

You could solve this by wrapping index in square brackets (ES6 syntax):

dict.push({ [index]: rate_1[index]})

Without this, index is indeed taken as a literal, not as the variable.

var categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"];
var rate_1 = [0.41,0.54,0.6,0.7,0.8];
var dict = [];
categories.forEach(function(ix,index){
  dict.push({[index]:rate_1[index]})
});
result = JSON.stringify(dict);
console.log(result);

As a side note: this code lends itself for using map instead of forEach, saving you the explicit array initialisation and push. I just provide this for info; it is not related to your question ;-)

var categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"];
var rate_1 = [0.41,0.54,0.6,0.7,0.8];
var dict = categories.map(function(ix,index){
  return {[index]:rate_1[index]};
});
result = JSON.stringify(dict);
console.log(result);