Skip to content

Instantly share code, notes, and snippets.

@aepyornis
Last active October 6, 2015 15:01
Show Gist options
  • Save aepyornis/c34c4529eecde79264c8 to your computer and use it in GitHub Desktop.
Save aepyornis/c34c4529eecde79264c8 to your computer and use it in GitHub Desktop.
Arrays and Properties
var _ = require('underscore');
var arr = [1,2,3,4]
arr.someProperty = "blah blah blah";
// this prints out only 1,2,3,4
_.each(arr, function(x){
console.log(x);
})
// and we can access .someProperty
console.log(arr.someProperty )
//but if we map arr
var timesTwo = _.map(arr, function(num){
return num * 2;
})
// everything seems to work like expected
console.log(timesTwo);
//but my someProperty is gone
console.log(timesTwo.someProperty);
// can I keep someProperty after I map my array?
// without having to do this hack:
var timesThree = _.map(arr, function(num){
return num * 3;
})
console.log(timesThree.someProperty) // undefined
timesThree.someProperty = arr.someProperty;
console.log(timesThree.someProperty) // "blah blah blah"
@aguestuser
Copy link

you found an interesting seam between the fact that javascript implements arrays as objects and the fact that when mapping over an array, it sort of only makes sense to output the actual elements of that array (qua array) from the computation. didn't know that underscore did that, but it's interesting!

why not something like this (a decorator pattern) to accomplish what you were after?

var wrapped = {
  prop: "blah blah blah",
  arr: [1,2,3,4]
};

_.extend(wrapped, { arr: _.map(wrapped.arr, function(n) { return n* 3; } ) } );

You keep the property you didn't want to lose, but you stick it inside a wrapping object that "decorates" the array in question with some new functionality you want. Does that do the trick? Or was there something important about keeping the property on the original array object that I'm missing?

@aepyornis
Copy link
Author

Another interesting underscore object/array thing:

_.map always returns an array. Even if you give it an object, it will always return an array.

But underscore has _.mapObject and loDash has _.mapValues which will return objects.

var arr = [1,2,3,4]
arr.someProperty = "blah blah blah";

_.mapObject(arr, function(x) {return x;}) // returns { '0': 1, '1': 2, '2': 3, '3': 4, someProperty: 'blah blah blah' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment