Concatenate array into string - javascript

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)

Related

convert array value to string value with javascript

I have an array
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
i want the result back as string
let strArr = "12,12,43,53,56,7,854,3,64,35,24,67"
Please some one suggest me any solution
You can use toString() method:
let arr = [12,12,43,53,56,7,854,3,64,35,24,67];
arr = arr.toString();
console.log(arr);
console.log(typeof arr);
You can read more about this here.
One solution is to use join method.
The join() method joins the elements of an array into a string, and
returns the string.
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
console.log(strArr);
Use Array.prototype.join().
The join() method joins all elements of an array (or an array-like object) into a string.
var a = [12,12,43,53,56,7,854,3,64,35,24,67];
a.join(); // '12,12,43,53,56,7,854,3,64,35,24,67'
JS type coercion is sometimes useful.
var arr = [12,12,43,53,56,7,854,3,64,35,24,67],
strArr = arr + ""; // <- "12,12,43,53,56,7,854,3,64,35,24,67"
Solution to this would be to use join()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
Second you be to use toString()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.toString();
Because you want to join by a comma, they are basically identical, but join allow you to chose a value separator.

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

Use an object-literal as array item

I have an object-literal like this
var data = {name:'racheal', class:'jss2', town:'kaduna'}
I would love this to be in an array like this
[{name:'racheal', class:'jss2', town:'kaduna'}]
You can just create an array with it:
var obj = {name:'racheal', class:'jss2', town:'kaduna'}
var arr = [obj];
Simple use of the push method on an array will achieve this:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [];
myArray.push(myObj);
Or, as Tushar says in comments, you can simply initialise a new array with the Object in it:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [myObj];
You can read a bit more on Arrays and their various methods and how to use them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

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