I have an object like this:
var person = {
name: \"John\",
surname: \"Smith\",
phone: \"253 689 4555\"
}
I want:
Write a function like this:
function toCSV(obj, separator) {
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
return arr.join(separator || ",");
}
And then you can call it like:
toCSV(person, "|"); // returns "John|Smith|253 689 4555"
or
toCSV(person); // returns "John,Smith,253 689 4555"
You can use this one-liner in modern browsers
Object.keys(person).map(function(k){return person[k]}).join(",");
This code will be useful when you want to extract some property values from an array of objects as comma separated string.
var arrayObjects = [
{
property1: "A",
property2: "1"
},
{
property1: "B",
property2: "2"
},
{
property1: "C",
property2: "3"
}
];
Array.prototype.map.call(arrayObjects, function(item) { return item.property1; }).join(",");
Output - "A,B,C"
Another way is to use lodash function _.toString()
console.log( _.toString( Object.values( person ) ) );
==> John,Smith,253 689 4555
Check the link below https://lodash.com/docs/4.17.5#toString