Perform .join on value in array of objects
If you want to map objects to something (in this case a property). I think Array.prototype.map
is what you're looking for if you want to code functionally.
console.log([ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ].map(function(elem){ return elem.name; }).join(","));
In modern JavaScript:
console.log([ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ].map(e => e.name).join(","));
If you want to support older browsers, that are not ES5 compliant you can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck
method:
var users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ];var result = _.pluck(users,'name').join(",")
Well you can always override the toString
method of your objects:
var arr = [ {name: "Joe", age: 22, toString: function(){return this.name;}}, {name: "Kevin", age: 24, toString: function(){return this.name;}}, {name: "Peter", age: 21, toString: function(){return this.name;}} ]; var result = arr.join(", "); console.log(result);
I've also come across using the reduce
method, this is what it looks like:
console.log( [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] .reduce(function (a, b) { return (a.name || a) + ", " + b.name} ))
The (a.name || a)
is so the first element is treated correctly, but the rest (where a
is a string, and so a.name
is undefined) isn't treated as an object.
Edit: I've now refactored it further to this:
x.reduce(function(a, b) {return a + ["", ", "][+!!a.length] + b.name;}, "");
which I believe is cleaner as a
is always a string, b
is always an object (due to the use of the optional initialValue parameter in reduce
)
Edit 6 months later: Oh what was I thinking. "cleaner". I've angered the code Gods.