-1

I am trying to append to a Javascript array in a loop.

I am writing this:

        var total_val = (unemployment_multi + laws_multi + family_multi + mobility_multi) / 5;
            country_vals.push({total_val:key});

But I end up having a bunch of objects with total_val as the key, rather than the value of total_val.

How do I create an array key with the value that is in total_val? Would I do something like country_vals.total_val.key or something?

EDIT: My goal is to have all of the values in total_val sortable by number - it is going to be a number from 1-10, and I want to sort in order of lowest to highest or highest to low (doesn't matter which), and each will have at least one of the key variable attached to it, but possibly more than one.

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232

2 Answers2

0

Try this:

country_vals[total_val] = key

Or:

total_val = ''+total_val
country_vals.push({total_val:key});
hamed
  • 7,939
  • 15
  • 60
  • 114
0

You need to use the bracket notation to create an object with dynamic keys

var total_val = (unemployment_multi + laws_multi + family_multi + mobility_multi) / 5;
var obj = {};
obj[total_val] = key;
country_vals.push(obj);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531