How to Convert Array of Objects into Comma Separated String extracting only one property

I’d like to share a quick solution which always is really useful when you are handling complex object-type data structures in JavaScript / ES6 / TypeScript.

That code will be useful when you want to extract some property values from an array of objects.

I will share two versions one for EcmaScript 5 and other for EcmaScript 6:

// ES5
var arrayObjects = [
{
name: "A",
surname: "1"
},
{
name: "B",
surname: "2"
},
{
name: "C",
surname: "3"
}
];
Array.prototype.map.call(arrayObjects, function(item) { return item.name; }).join(","); // "A,B,C"
// ES6 / TypeScript
const arrayObjects = [
{
name: "A",
surname: "1"
},
{
name: "B",
surname: "2"
},
{
name: "C",
surname: "3"
}
];
Array.prototype.map.call(arrayObjects, s => s.name).toString(); // "A,B,C"

 

Author: José Quinto
Link: https://blog.josequinto.com/2017/03/17/how-to-convert-array-of-objects-into-comma-separated-string-extracting-only-one-property/
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.