D
danielbigg
I am new to JavaScript but not to programming. What's the best way of
getting an array of all the values for an attribute in an object
array? I was thinking of using map, e.g.:
var points = [{x: 1, y: 3}, {x: 2, y: 2}, {x: 3, y: 1}];
alert(points.map(function(p){return p.x;}));
alert(points.map(function(p){return p.y;}));
JavaScript seems to be full of all sorts of neat tricks and I would be
surprised if there wasn't a more standard way of doing this without
resorting to loops. Anyone have any ideas?
N.B. I am using the following definition of map:
// This prototype is provided by the Mozilla foundation and
// is distributed under the MIT license.
// http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res = fun.call(thisp, this, i, this);
}
return res;
};
}
getting an array of all the values for an attribute in an object
array? I was thinking of using map, e.g.:
var points = [{x: 1, y: 3}, {x: 2, y: 2}, {x: 3, y: 1}];
alert(points.map(function(p){return p.x;}));
alert(points.map(function(p){return p.y;}));
JavaScript seems to be full of all sorts of neat tricks and I would be
surprised if there wasn't a more standard way of doing this without
resorting to loops. Anyone have any ideas?
N.B. I am using the following definition of map:
// This prototype is provided by the Mozilla foundation and
// is distributed under the MIT license.
// http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res = fun.call(thisp, this, i, this);
}
return res;
};
}