'Print specific property of all objects in an array using join

I have the following code -

var test = [ { id:'1', name: 'a'},  { id:'2' name: 'b'},  { id:'3', name: 'c'}];
alert(test.join(', '));

How do I alert a, b, c? Right now, I get -

[Object, Object, Object]


Solution 1:[1]

If your browser supports ECMAScript 5 (Internet Explorer 8 and lower do not), you can use map():

alert(test.map(function(obj) {
    return obj.name;
}).join(", "));

Solution 2:[2]

You can map each object in your array to the name property that you want to print and use an arrow function for conciseness.

var test = [{id: '1', name: 'a'}, {id: '2', name: 'b'}, {id:'3', name: 'c'}];
alert(test.map(o => o.name).join(", "));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frédéric Hamidi
Solution 2 VHS