convert an string to a array in javascript? - javascript

I'm trying to convert a string to an array in javascript?
var strng = "[a,b]"
Expected output:
var arry = ["a","b"]

Work for all string like "[a,b]" or "[a,b,c,d]"
var strng = "[a,b]";
console.log(strng.replace(/\[|]/g, "").split(","));

Try this:
var strng = "[a,b]";
let arr = strng.slice(1,-1).split(",");
console.log(arr);

Related

Javascript Get all number from array

From Array get only number into a new array or a string
var fetchMIDarray = [
'Corp: nameofthecompany (345961663886)',
'Chain: somerandomname (372395416889)'
]
except result for new array should be:
var fetchnumber =['345961663886','372395416889']
I know how this works for the string but unable to do same for array
code sinppet for string.
var midname='Corp: Best Buy ApplePay/Partsearch (345961663886)';
var matches2 = midname.match(/\d+/);
console.log(matches2);
You can use Array#map.
let arr = ['Corp: nameofthecompany (345961663886)', 'Chain: somerandomname (372395416889)'];
let res = arr.map(x => x.match(/\d+/)[0]);
console.log(res);

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

How to add string to array?

Example:
var imageBounds = [[40.712216, -74.22655], [46.773941, -79.12544]];
I need to create same from js. The problem that I am getting data in string format:
[40.712216, -74.22655], [46.773941, -79.12544]
so:
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]"
Ok, lets create empty array:
var myarr = []; // empty array
but how to add data to it? I know about push method but it's work only with arrays, and I have got text.
Make it valid JSON (by adding [ at beginning and ] at ending) afterward parse the string using JSON.parse method.
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]";
var res = JSON.parse('[' + mystr + ']');
console.log(res);

javascript comma separated list to array

I have this type of list from javascript:
Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina
I used the following code to convert to my output
var array = columnsload.split(",");
var string = JSON.stringify(columnsload);
var nameArray = string.split(',');
The output is like this :
"Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina"
But I really need it like this :
["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
Anyone know how to get output like this?
the split function is enough to convert the string into an array;
var names = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArr = names.split(",");
console.log( nameArr );
http://www.w3schools.com/jsref/jsref_split.asp
Just do var nameArray = columnsload.split(',');. You dont need to stringify the array and then split it again, just one .split would be enough.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(nameArray);
If you need the whole thing to be string, you can run a JSON.stringify on the array after.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(JSON.stringify(nameArray));
// outputs ["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
// as one string.

Convert string into array of object in javascript

Need to convert string into array of object in JavaScript. Here is the example,
var str = "1,2";
output:
"values":[
{"id":"1"},
{"id":"2"}
];
Make use of map():
var str = "1,2";
var s = str.split(',').map(function(x){
return {"id" : x};
})
str = {"values" : s};
console.log(JSON.stringify(str));
try this:
var str = "1,2";
str = str.split(",");
var obj = {'value':[]};
str.forEach(function(val){
obj.value.push({'id':val})
});
str = "1,2"
var res = str.split(",");
values = []
for each (var item in res ) {
values .push({
id: item
});
}
console.log(JSON.stringify(values));
use split , list push and loop
Use map. Both split (for converting the string to an array) and map (which returns a new array for each element of the array that is passed through the provided function) are chainable so you can do the following:
var values = str.split(',').map(function (el) {
return { id: el };
});
DEMO
It's not clear whether you want just an array of objects, or a JSON string of that array. If it's the latter, use JSON.stringify(result).

Categories

Resources