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);
Videos
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);
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)
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.
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(', '))
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.
You need to parse the string you get from the sessionStorage, then you can map and join:
var profile = '{"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]}'; // sessionStorage.getItem("profile");
var dataResidence = JSON.parse(profile);
function mapAndJoin(arr, key) {
return arr.map(function(o) {
return o[key];
}).join();
}
var domiciles = mapAndJoin(dataResidence.domiciles, 'country');
var investor = mapAndJoin(dataResidence.investor, 'type');
console.log(domiciles);
console.log(investor);
One way of doing it
var obj={"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]};
console.log(JSON.stringify(obj));
var countries = obj.domiciles;
var str = '';
for(i=0;i<countries.length;i++){
if(i != countries.length - 1)
str+= countries[i].country+",";
else
str += countries[i].country;
}
console.log(str);
var type = obj.investor;
var str1 = '';
for(i=0;i<type.length;i++){
if(i != type.length - 1)
str1 += type[i].type+",";
else
str1 += type[i].type;
}
console.log(str1);