0

What I'm trying to achieve:
Create an array for each country 'item_location' and push object values with 'item_location' as the key.

e.g

[{USA:1},{USA:2}], [{UK:1},{UK:2}], [{CUBA:1},{CUBA:2}]

or

e.g

[
 {
  USA: {"Activity/Adventure": 1, "Beach Escape": 2}, 
  UK: {"Activity/Adventure": 1, "Beach Escape": 2}, 
  CUBA: {"Activity/Adventure": 1, "Beach Escape": 2}
 }
]



Current Problems:
The object key says 'item_location' instead of picking up the 'item_location' var value 'item.Location'.

  var filter = [];
  for(var ix = 0; ix < jsonData.length; ix++)
    {
      var item = jsonData[ix];
      var item_location = item.Location;
      var item_ = [{item_location:item["Activity/Adventure"]},{item_location:item["Beach Escape"]}];
      filter.push({item_});
    }
  console.log(filter);

enter image description here

ANWSER:

function filterData(){
  var filter = [];
  for(var ix = 0; ix < jsonData.length; ix++)
    {
      var item = jsonData[ix];
      var item_location = item.Location;
      var item1 = {}, item2= {};

      item1[item_location] = item["Activity/ Adventure"];
      item2[item_location] = item["Beach Escape"];
      var item_ = [item1, item2];

      filter.push(item_);
    }
  console.log(filter);
}
  • Is that one array of arrays, or multiple arrays each containing two objects? And what does the `jsonData` object contain? – David Thomas Sep 01 '15 at 16:28
  • This has been surely answered here. But a quick solution : Use `item_[item_location] = item[".."]` .. and so on. Here you go http://stackoverflow.com/a/695053/3639582 – Shaunak D Sep 01 '15 at 16:32

1 Answers1

0

The key is item_location because that's what you set it to. You cannot use variables as key names in an object literal.

You'd need to make a new object, then use the obj[key] syntax to add the key.

var item_location = item.Location;
var item1 = {}, item2= {};

item1[item_location] = item["Activity/Adventure"];
item2[item_location] = item["Beach Escape"];
var item_ = [item1, item2];

filter.push(item_);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Missing: var item = jsonData[ix]; but once added this worked perfectly! Thank you. –  Sep 02 '15 at 08:19
  • @adamkwadsworth: You're welcome. Guess I just missed copying & pasting a few lines from the original question :-P – gen_Eric Sep 02 '15 at 13:40