Last active
October 6, 2015 15:01
-
-
Save aepyornis/c34c4529eecde79264c8 to your computer and use it in GitHub Desktop.
Arrays and Properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
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
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?
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?