Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
var json = [];
var to = '[email protected],[email protected],[email protected]';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
json.push({"email":toSplit[i]});
}
Try this ES6 Version which has better perform code snippet.
'use strict';
let to = '[email protected],[email protected],[email protected]';
let emailList = to.split(',').map(values => {
return {
email: values.trim(),
}
});
console.log(emailList);
Get comma separated string from array
How to get convert json array to comma separated values
javascript - JSON Object into Comma Separated String
How to get a comma separated list from a JSON response?
What you need is this:
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x]);
console.log(res.join(","));
And there's one more way of 'elegantly' doing it (taken from Alex's answer),
res = [];
Object.keys(obj).forEach(function(key) {
res.push(obj[key]);
});
console.log(res.join(","));
In case you need the result in that specific order, sorting the keys (that come from Object.keys(obj)) before invoking forEach on the array will help. Something like this:
Object.keys(obj).sort().forEach(function(key) {
This is very simple in Javascript. You can access the variable data like this:
alert(data[0]);
which should alert "San Diego acls". Do the same for all of them using a loop. You can concatenate strings easily with the + operator.
var result = "";
for (var dString in data) {
result += dString + ", ";
}
This will create a string called result and add the elements of the strings in the array to it. It will also add ", " between each element as you described in the question.
This can be achieved via the join() method which is built into the Array type:
const object = {
"id" : "122223232244",
"title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ",
"data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]
}
/* Join elements of data array in object to a comma separated string */
const value = object.data.join();
console.log(value);
If no separator argument is supplied, then the join() method will default to use a comma separator by default.
Update
If the JSON was supplied in raw text via a string you can use the JSON.parse() method to extract an object from the JSON string value as a first step like so:
const json = `{"id" : "122223232244","title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ","data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]}`
/* Parse input JSON string */
const object = JSON.parse(json);
/* Join elements of data array in object to a comma separated string */
const value = object.data.join();
console.log(value);
Access object properties using dot notation (e.g. obj.data) and then on the array you can use join to convert to a string with a comma in between.
const obj = {
"id" : "122223232244",
"title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ",
"data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]
}
console.log(obj.data.join(', '))
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
Actually, the toString() implementation does a join with commas by default:
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.
In JavaScript, you can convert an array to a string with commas using the join()
method.
The join() method returns a string that concatenates all the elements of an array, separated by the specified separator, which in this case is a comma.
Here is an example:
const array = ['apple', 'banana', 'orange'];
const string = array.join(', ');
console.log(string);
// output: "apple, banana, orange"
In this example, we first define an array of three fruits. Then we use the join()
method with a comma and a space as the separator to create a string that lists all the fruits with a comma and a space between each one.
You can replace the comma and space separator with any other separator you like, such as a hyphen, a semicolon, or a newline character.
It's important to note that the join() method only works on arrays, and it will throw an error if you try to use it on any other type of object.
Click here to learn more ways to Convert Array to String with Commas in JS
The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"
Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:
//will implicitly call array.toString()
str = ""+array;
str = `${array}`;
Array.prototype.join()
The join() method joins all elements of an array into a string.
Arguments:
It accepts a separator as argument, but the default is already a comma ,
str = arr.join([separator = ','])
Examples:
var array = ['A', 'B', 'C'];
var myVar1 = array.join(); // 'A,B,C'
var myVar2 = array.join(', '); // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join(''); // 'ABC'
Note:
If any element of the array is undefined or null , it is treated as an empty string.
Browser support:
It is available pretty much everywhere today, since IE 5.5 (1999~2000).
References
- ECMA Specification
- Mozilla
- MSDN
Use the join method from the Array type.
a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();
The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.
You can use .slice():
> var a = [1, 2, 3, 4, 5];
> [a.slice(0, -1).join(', '), a.slice(-1)[0]].join(a.length < 2 ? '' : ' and ');
'1, 2, 3, 4 and 5'
a.slice(0, -1).join(', '): takes all but the last element and joins them together with a comma.a.slice(-1)[0]: it's the last element..join(a.length < 2 ? '' : ' and '): joins that string and the last element withandif there are at least two elements.
Another quick solution is to replace the last comma with and.
The following code:
var a = [0,1,2,3,4];
a.join(', ').replace(/,(?!.*,)/gmi, ' and');
should do the trick. (Also, play with the regex modifiers to your need).
One probable issue might be of time when you have large array, but it should work.
const array = str.split(',');
MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)
Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.
var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");
Adding a loop like this,
for (a in temp ) {
temp[a] = parseInt(temp[a], 10); // Explicitly include base as per รlvaro's comment
}
will return an array containing integers, and not strings.