I have an object that looks like this:
{
"id": "123",
"members": [
{ "id": 1, "name": "Andrew" },
{ "id": 2, "name": "Jim" }
]
}
I'd like a method to return a string of member names: "Andrew, Jim"
.
As opposed to iterating through the member list and adding them to an array, is there a way to accomplish this cleanly in a single line (maybe underscore.js)?
To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator. Copied!
The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.
Array join() method This method joins the elements of the array to form a string and returns the new string. The elements of the array will be separated by a specified separator. If not specified, Default separator comma (, ) is used.
How to get comma separated values from an array of objects in JavaScript? A simple way of achieving it is by using the map () and join () JavaScript functions:The map () method ...
If not used, Separated Comma (, ) is used. A String, containing the array values, separated by the specified separator. This method converts an array into a String and returns the new string.
The elements of the array will be separated by a specified separator. If not specified, Default separator comma (, ) is used. separator: This parameter is optional. It specifies the separator to be used. If not used, Separated Comma (, ) is used. A String, containing the array values, separated by the specified separator.
A simple way of achieving it is by using the map () and join () JavaScript functions:The map () method ... There are times you want to get comma (or another character) delimited values from a given field in ...
members
is Array
of Objects
, first you need to create Array
with names - for this case you can use .map
and then convert this Array
to String
- to do that you can use .join
var data = {
"id": "123",
"members": [
{ "id": 1, "name": "Andrew" },
{ "id": 2, "name": "Jim" }
]
};
var result = data.members.map(function (e) {
return e.name;
}).join(', ');
console.log(result);
something like
var arr = {
"id": "123",
"members": [
{ "id": 1, "name": "Andrew" },
{ "id": 2, "name": "Jim" }
]
};
console.log( arr.members.reduce( function(x,y){ return "\"" + x.name + "\", \"" + y.name + "\"" } ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With