This will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
Answer from joeltine on Stack OverflowThis will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.
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);
json - How to return comma delimited string from array, in React, javascript? - Stack Overflow
How can I convert a comma-separated string to an array?
Convert string separated by comma in json object to array
JavaScript: How to get comma separated string from json string? - Stack Overflow
const str = `"${users.map(x => x.name).join('", "')}"`;
Which uses a template string to give the leading and trailing quotes with the joined array inbetween. Ungolfed:
let str = '"'; // prepend "
str += users
.map(x => x.name) // get the name from the user objs
.join('", "') // join with the double quote and comma
str += '"'; // closing "
I would use a reduce function as that is used to reduce an array to a single output. If it is the first item (index == 0), then just return the name to the accumulator (which kind of stores the string and appends to it as you go through the array) with quotation marks on either side (escaped with \ but not necessary if using single quotes), else return the accumulator with a comma and a quotation mark after it as well as the name and another quotation mark.
So as you go through the array, the accumulator will be something like this:
- "John"
- "John","Tim"
- "John","Tim","Mike"
and when it gets to the end, it returns it to the variable, so commaSeparatedString == "\"John\",\"Tim\",\"Mike\""
const users = [{
"name": "John",
"color": "blue",
}, {
"name": "Tim",
"color": "red",
}, {
"name": "Mike",
"color": "green",
}];
const commaSeparatedString = users.reduce(function(accumulator, currentValue, index) {
return index == 0
? '\"' + currentValue.name + '\"'
: accumulator + ',\"' + currentValue.name + '\"';
}, '');
console.log(commaSeparatedString);
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.
You can do the following,
data = [
{'id': 1,
'name': 'book',
'colors': 'red, yellow, blue'
},
{'id': 2,
'name': 'book',
'colors': 'red, yellow, blue'
}
];
ret = data.map((item) => {
return {...item, colors: item.colors.split(',').map(item => item.trim())};
})
console.log(ret);
Strings get into arrays in each object.
let arr = [
{id: 1,
name: 'book',
colors: 'red, yellow, blue'
},
{id: 2,
name: 'book',
colors: 'red, yellow, blue'
}
]
for (let index in arr) {
let colorsIntoArr = arr[index].colors.split(',');
arr[index].colors = colorsIntoArr;
}
/*
[
{
"id": 1,
"name": "book",
"colors": [
"red",
" yellow",
" blue"
]
},
{
"id": 2,
"name": "book",
"colors": [
"red",
" yellow",
" blue"
]
}
]
*/
console.log(arr)
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(', '))
i think this can be done by regEx by i don't how to look it up.
this is a learning project, but i am just thinking about the scale
i have a form where the user enter a bunch of categories and i want the user to separate those categories with a comma, but working on the case where the user add the comma but also a space after the comma (as we all do) or before the comma, how to go about treating this case, because i don't want to end up with two or three categories that are the same.
edit: i did it but i don't want to remove the post to help anyone with the same issue.
here's what i did
const categoriesAsString = e.target.value;
const categoriesTrimmed = categoriesAsString.trim();
const categoriesAsStringWithWhiteSpace = categoriesTrimmed.replace(/\s*,\s*/g,",");
const categoriesAsArray = categoriesAsStringWithWhiteSpace.split(",");
setCategories(categoriesAsArray);
Try:
var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");
Use the split function which is available for strings and convert the numbers to actual numbers, not strings.
var ar = "'California',51.2154,-95.2135464,'data'".split(",");
for (var i = ar.length; i--;) {
var tmp = parseFloat(ar[i]);
ar[i] = (!isNaN(tmp)) ? tmp : ar[i].replace(/['"]/g, "");
}
console.log(ar)
Beware, this will fail if your string contains arrays/objects.