How to add string to array? - javascript

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);

Related

how to convert string in to json array in angularjs

image name
021D3BB2995711E7BFD706E21CB7534C---FEATURED_IMAGE__images.jpg
**this image name convert into json aray and output like this **
[“021D3BB2995711E7BFD706E21CB7534C---FEATURED_IMAGE__images.jpg”]
I might not get your question 100%, but if you have a String and want it to be in an array, you can use the .push() method.
var myString = 'hello';
console.log(myString); // hello
var myArray = [];
myArray.push(myString);
console.log(myArray); // ['hello']
myArray = JSON.stringify(myArray);
console.log(myArray); // "["hello"]"
Try it.
str='021D3BB2995711E7BFD706E21CB7534C---FEATURED_IMAGE__images.jpg';
var jsonObj = $.parseJSON('[' + str + ']');

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)

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).

Javascript/Jquery Convert string to array

i have a string
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
i tried
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?
Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
​for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}​

Categories

Resources