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.
(fiddle)
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(",")
Answer from Benjamin Gruenbaum on Stack OverflowIf 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.
(fiddle)
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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
javascript - Join array of objects - Stack Overflow
javaScript Array.join("")
Merge Array of objects that have the same properties
How can I merge two arrays of different objects but equal length?
Edited to reflect that b can be smaller but never larger than a.
function merge(a,b){
//Don't want to mutate a
var result = a.slice();
for(var i = 0; i < b.length; i++){
for (var attrname in b[i]) {
result[i][attrname] = b[i][attrname];
}
}
return result;
}
Code partly taken from accepted answer in: How can I merge properties of two JavaScript objects dynamically?
Assuming that the two arrays have the same length, an in place merge could be something like this:
var a = [{ x: 0, y: 0, color: "green", value: undefined, weight: 1 }, { x: 0, y: 1, color: "red", value: undefined, weight: 1 }];
var b = [{ x: 0, y: 0, value: 1, weight: 1 }, { x: 0, y: 1, value: 3, weight: 1 }];
function merge_objects(o1, o2) {
Object.keys(o2).forEach(
function(key) {
o1[key] = o2[key];
});
}
function merge(a, b) {
if (a.length != b.length) {
throw new Error();
}
for (var ix=0; ix<a.length; ix++) {
merge_objects(a[ix], b[ix]);
}
}