Using map functionality you can join the array of objects in JavaScript. Code snip for join object values.
console.log([
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
].map(function(elem){
return elem.name;
}).join(","));
In modern JavaScript, this will not perform with the join
method only on the name
attribute, to achieve the same output as before.
console.log([
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
].map(e => e.name).join(","));
Source: stackoverflow.com
Example join an array of objects in JavaScript
A simple example code uses the .join()
method to get a single string, with each element separated by commas, like so:
["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"
If you want to perform a similar operation on a value held within it.
[
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
Complete code
<!DOCTYPE html>
<html>
<head>
<script>
let arr = [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
let res = arr.map(function(elem){
return elem.name +" "+ elem.age; }).join(",");
console.log(res)
</script>
</head>
</html>
Output:
Do comment if you have any doubt or suggestions on this JS join array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version