cheapsteak
6/5/2014 - 2:09 AM

Turning a normal array into an associative array using aribitrary property

Turning a normal array into an associative array using aribitrary property

Given

var countries = [
  {
    country: "Canada",
    capital: {
      name: "Ottawa",
      population: 883391
    }
  },
  {
    country: "China",
    capital: {
      name: "Beijing",
      population: 11510000
    }
  },
  {
    country: "Australia",
    capital: {
      name: "Canberra",
      population: 358222
    }
  }
];

Increase lookup speed at the cost of looping once through the entire array by creating an index on capital name.


var countriesMappedByCapital = _(countries).indexBy(function (country) {
  return country.capital.name
});

value of countriesMappedByCapital:

{
  "Ottawa": {
    "country": "Canada",
    "capital": {
      "name": "Ottawa",
      "population": 883391
    }
  },
  "Beijing": {
    "country": "China",
    "capital": {
      "name": "Beijing",
      "population": 11510000
    }
  },
  "Canberra": {
    "country": "Australia",
    "capital": {
      "name": "Canberra",
      "population": 358222
    }
  }
}

If indexed items are not unique, items towards the end of the array will overwrite the existing mapped reference

var countries = [
  {
    country: "Israel",
    capital: {
      name: "Jerusalem",
      population: 7908000
    }
  },
  {
    country: "Palestine",
    capital: {
      name: "Jerusalem",
      population: 4047000
    }
  }
];

var countriesMappedByCapital = _(countries).indexBy(function (country) {
  return country.capital.name
});

value of countriesMappedByCapital:

{
  "Jerusalem": {
    "country": "Palestine",
    "capital": {
      "name": "Jerusalem",
      "population": 4047000
    }
  }
}