0

I'm refactoring some code that currently has these three variables:

var sites=["London","Dublin","Paris"];
var mostRecent = {London: '',Dublin: '',Paris: ''};
var ackStatus = {London: '',Dublin: '',Paris: ''};

That seems unnecessarily verbose, and makes adding a site difficult, so I combined them into one array of objects here:

var sites = [
{name: 'London', mostRecent:'', ackStatus:''},
{name: 'Dublin', mostRecent:'', ackStatus:''},
{name: 'Paris', mostRecent:'', ackStatus:''}
];

How do I choose an object to update based on the site name? The variables are currently being accessed like this:

ackStatus["London"] = xmlhttp.responseText;

Alternatively, is there a better way to refactor this than what I did? Three arrays is not terrible, but if the code expands much more, it will get confusing.

  • 4
    I'd suggest `{London: {mostRecent: '', ...}, Dublin: {mostRecent: '', ...}, ...}` as structure. Then you can use the same way of accessing the object: `sites.London`. Otherwise you have to iterate over the array and find the object with `name === 'London'`. – Felix Kling Feb 13 '14 at 19:34
  • @Felix Kling I tried declaring like this: `var sites = [ London: {mostRecent:'011', ackStatus:''}, Dublin: {mostRecent:'100', ackStatus:''} ];` And also tried like this: `var sites = [ {London: {mostRecent:'011', ackStatus:''}}, {Dublin: {mostRecent:'100', ackStatus:''}} ];` And I'm still not sure how to access them. This doesn't work: `sites.London.mostRecent` – Katherine Skipper Feb 13 '14 at 19:41
  • Like I wrote: `var sites = {London: {mostRecent: '', ...}, Dublin: {mostRecent: '', ...}, ... };`. Your first try is invalid syntax, you uses `[ ]` instead of `{ }`. The second is again an array of objects. – Felix Kling Feb 13 '14 at 19:44
  • That worked, thank you! Is there also a way to access them by an index number? The first array is used to call a function once for each site name, using `for (x=0;x – Katherine Skipper Feb 13 '14 at 19:51
  • No, but you can use a `for...in` loop to iterate over the properties of an object. – Felix Kling Feb 13 '14 at 19:53
  • You can access it the same way you were before with bracket notation: `sites[x]` would be the same as something like `sites.city`. Then use `sites[x].mostRecent` to update that property – brouxhaha Feb 13 '14 at 19:55
  • Isn't that only if I declare an array like `var sites[]` and not `sites{}`? – Katherine Skipper Feb 13 '14 at 20:02
  • Also, accessing a literal like `sites.London.mostRecent` works, but using a variable doesn't: `var city = "London"; sites.city.mostRecent` – Katherine Skipper Feb 13 '14 at 20:04
  • That's what bracket notation is for: `sites[city].mostRecent`. Have a look at http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json. – Felix Kling Feb 13 '14 at 21:40

0 Answers0