Tech Is Hard

Credibility = Talent x Years of experience + Proven hardcore accomplishment

Reducing an Array of Objects to a Hash Using a Property as Key


I don’t know if this is obvious, but it’s a pretty cool, quick way to take an array of objects and get them keyed by some field in the object.  Assume an array of objects, foo.  Using Underscore.js’s reduce() function, we’ll create three different hashes, each using a different field in foo’s objects as the key.

var foo = [
 {name: 'John', phone: '555-1234', social: '299-99-0123'},
 {name: 'Sally', phone: '555-5465', social: '399-99-0123'},
 {name: 'Fred', phone: '555-4356', social: '499-99-0123'},
 {name: 'Lisa', phone: '555-2318', social: '299-99-1234'},
 {name: 'Ambrose', phone: '555-9023', social: '299-99-4352'}
 ];

console .log ( _.reduce (foo, function (reduced, item) {
 reduced[item.name] = item;
 return reduced;
}, {}));
console .log ( _.reduce (foo, function (reduced, item) {
 reduced[item.phone] = item;
 return reduced;
}, {}));
console .log ( _.reduce (foo, function (reduced, item) {
 reduced[item.social] = item;
 return reduced;
}, {}));

The log looks like:

Object
  1. Ambrose: Object
    1. name: “Ambrose”
    2. phone: “555-9023”
    3. social: “299-99-4352”
  2. Fred: Object
    1. name: “Fred”
    2. phone: “555-4356”
    3. social: “499-99-0123”
  3. John: Object
    1. name: “John”
    2. phone: “555-1234”
    3. social: “299-99-0123”
  4. Lisa: Object
    1. name: “Lisa”
    2. phone: “555-2318”
    3. social: “299-99-1234”
  5. Sally: Object
    1. name: “Sally”
    2. phone: “555-5465”
    3. social: “399-99-0123”
Object
  1. 555-1234: Object
  2. 555-2318: Object
  3. 555-4356: Object
  4. 555-5465: Object
  5. 555-9023: Object
Object
  1. 299-99-0123: Object
  2. 299-99-1234: Object
  3. 299-99-4352: Object
  4. 399-99-0123: Object
  5. 499-99-0123: Object
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: