In a chain of array manipulation methods, I'd like to alter a property of each item in the array.
Each of the available methods has a problem when used this way:
- Array.prototype.forEach doesn't return the array
- Array.prototype.map requires that each item is returned
- Array.prototype.filter requires that a "true" value is returned for each item
Does Array have a method that allows each item in an array to be manipulated, and returns the array?
I've resorted to using either map
or filter
, but that feels like a workaround which shouldn't be necessary.
A contrived example:
var items = [
{ name: 'Smith' },
{ name: 'Jones' },
{ name: 'Simpson' }
];
filter:
return items.filter(function(item) {
item.fullname = 'Professor ' + item.name;
return true;
});
map:
return items.map(function(item) {
item.fullname = 'Professor ' + item.name;
return item;
});
forEach:
items.forEach(function(item) {
item.fullname = 'Professor ' + item.name;
});
return items;
??:
return items.someMethod(function(item) {
item.fullname = 'Professor ' + item.name;
});