Skip to content Skip to sidebar Skip to footer

Javascript Turn Property Of Objects In Array Into A String

I have an array of objects which are all instances of the same class like below: class Foo { constructor(bar){ this.bar = bar; } } var myArr = [new Foo('1'), new F

Solution 1:

You can use Array.prototype.map:

var result = myArr.map(function(x) { return x.bar; }).join(',');

Solution 2:

You could use Array.prototype.reduce:

var result = myArr.reduce(function(acc, el) {
 if(!acc) return el.bar;
 return acc + ', ' + el.bar;
}, '');

Solution 3:

The alternative solution using Array.reduce function:

var barValues = myArr.reduce((a,b) => (a['bar'] || a) + "," + b['bar']);
console.log(barValues);  // "1,2,3,4"

Post a Comment for "Javascript Turn Property Of Objects In Array Into A String"