Related
How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Most modern browsers support this method natively, but for those that don't, you can include a JS version.
Use javascript String() function
String(yourobject); //returns [object Object]
or stringify()
JSON.stringify(yourobject)
Sure, to convert an object into a string, you either have to use your own method, such as:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604
or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.
Update:
A more modern solution would be:
function objToString (obj) {
let str = '';
for (const [p, val] of Object.entries(obj)) {
str += `${p}::${val}\n`;
}
return str;
}
or:
function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
Keeping it simple with console, you can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console.
Example:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
Output:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
One option:
console.log('Item: ' + JSON.stringify(o));
Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:
console.log('Item: ', o);
None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.
I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.
//Make an object a string that evaluates to an equivalent object
// Note that eval() seems tricky and sometimes you have to do
// something like eval("a = " + yourString), then use the value
// of a.
//
// Also this leaves extra commas after everything, but JavaScript
// ignores them.
function convertToText(obj) {
//create an array that will later be joined into a string.
var string = [];
//is object
// Both arrays and objects seem to return "object"
// when typeof(obj) is applied to them. So instead
// I am checking to see if they have the property
// join, which normal objects don't have but
// arrays do.
if (typeof(obj) == "object" && (obj.join == undefined)) {
string.push("{");
for (prop in obj) {
string.push(prop, ": ", convertToText(obj[prop]), ",");
};
string.push("}");
//is array
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
string.push("[")
for(prop in obj) {
string.push(convertToText(obj[prop]), ",");
}
string.push("]")
//is function
} else if (typeof(obj) == "function") {
string.push(obj.toString())
//all other values can be done with JSON.stringify
} else {
string.push(JSON.stringify(obj))
}
return string.join("")
}
EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:
Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.
Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.
If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.
In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.
For example the following would convert all items in "value" to a string:
$.each(this, function (name, value) {
alert(String(value));
});
More details here:
http://www.w3schools.com/jsref/jsref_string.asp
I was looking for this, and wrote a deep recursive one with indentation :
function objToString(obj, ndeep) {
if(obj == null){ return String(obj); }
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return '{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray];
default: return obj.toString();
}
}
Usage : objToString({ a: 1, b: { c: "test" } })
var obj={
name:'xyz',
Address:'123, Somestreet'
}
var convertedString=JSON.stringify(obj)
console.log("literal object is",obj ,typeof obj);
console.log("converted string :",convertedString);
console.log(" convertedString type:",typeof convertedString);
There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:
console.log('Item: %o', o);
I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).
If you just want to see the object for debugging, you can use
var o = {a:1, b:2}
console.dir(o)
1.
JSON.stringify(o);
Item: {"a":"1", "b":"2"}
2.
var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);
Item: {a:1, b:2}
It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});
JSON methods are quite inferior to the Gecko engine .toSource() primitive.
See the SO article response for comparison tests.
Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).
(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)
javascript:
Object.prototype.spoof=function(){
if (this instanceof String){
return '(new String("'+this.replace(/"/g, '\\"')+'"))';
}
var str=(this instanceof Array)
? '['
: (this instanceof Object)
? '{'
: '(';
for (var i in this){
if (this[i] != Object.prototype.spoof) {
if (this instanceof Array == false) {
str+=(i.match(/\W/))
? '"'+i.replace('"', '\\"')+'":'
: i+':';
}
if (typeof this[i] == 'string'){
str+='"'+this[i].replace('"', '\\"');
}
else if (this[i] instanceof Date){
str+='new Date("'+this[i].toGMTString()+'")';
}
else if (this[i] instanceof Array || this[i] instanceof Object){
str+=this[i].spoof();
}
else {
str+=this[i];
}
str+=', ';
}
};
str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
(this instanceof Array)
? ']'
: (this instanceof Object)
? '}'
: ')'
);
return str;
};
for(i in objRA=[
[ 'Simple Raw Object source code:',
'[new Array, new Object, new Boolean, new Number, ' +
'new String, new RegExp, new Function, new Date]' ] ,
[ 'Literal Instances source code:',
'[ [], {}, true, 1, "", /./, function(){}, new Date() ]' ] ,
[ 'some predefined entities:',
'[JSON, Math, null, Infinity, NaN, ' +
'void(0), Function, Array, Object, undefined]' ]
])
alert([
'\n\n\ntesting:',objRA[i][0],objRA[i][1],
'\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
'\ntoSource() spoof:',obj.spoof()
].join('\n'));
which displays:
testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
new RegExp, new Function, new Date]
.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
/(?:)/, (function anonymous() {}), (new Date(1303248037722))]
toSource() spoof:
[[], {}, {}, {}, (new String("")),
{}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]
and
testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]
.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]
toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]
and
testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]
.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
function Function() {[native code]}, function Array() {[native code]},
function Object() {[native code]}, (void 0)]
toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]
For non-nested objects:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
stringify-object is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object
npm install stringify-object
then:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Obviously it's interesting only if you have circular object that would fail with JSON.stringify();
As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj) :
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
If you only care about strings, objects, and arrays:
function objectToString (obj) {
var str = '';
var i=0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(typeof obj[key] == 'object')
{
if(obj[key] instanceof Array)
{
str+= key + ' : [ ';
for(var j=0;j<obj[key].length;j++)
{
if(typeof obj[key][j]=='object') {
str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
}
else
{
str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
}
}
str+= ']' + (i > 0 ? ',' : '')
}
else
{
str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
}
}
else {
str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
}
i++;
}
}
return str;
}
maybe you are looking for
JSON.stringify(JSON.stringify(obj))
"{\"id\":30}"
Take a look at the jQuery-JSON plugin
At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.
If you can use lodash you can do it this way:
> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'
With lodash map() you can iterate over Objects as well.
This maps every key/value entry to its string representation:
> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]
And join() put the array entries together.
If you can use ES6 Template String, this works also:
> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'
Please note this do not goes recursive through the Object:
> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]
Like node's util.inspect() will do:
> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
function objToString (obj) {
var str = '{';
if(typeof obj=='object')
{
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + ':' + objToString (obj[p]) + ',';
}
}
}
else
{
if(typeof obj=='string')
{
return '"'+obj+'"';
}
else
{
return obj+'';
}
}
return str.substring(0,str.length-1)+"}";
}
var o = {a:1, b:2};
o.toString=function(){
return 'a='+this.a+', b='+this.b;
};
console.log(o);
console.log('Item: ' + o);
Since Javascript v1.0 works everywhere (even IE)
this is a native approach and allows for a very costomised look of your object while debugging and in production
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
Usefull example
var Ship=function(n,x,y){
this.name = n;
this.x = x;
this.y = y;
};
Ship.prototype.toString=function(){
return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};
alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523
Also, as a bonus
function ISO8601Date(){
return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6 Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29
Circular References
By using below replacer we can produce less redundant JSON - if source object contains multi-references to some object, or contains circular references - then we reference it by special path-string (similar to JSONPath) - we use it as follows
let s = JSON.stringify(obj, refReplacer());
function refReplacer() {
let m = new Map(), v= new Map(), init = null;
return function(field, value) {
let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field);
let isComplex= value===Object(value)
if (isComplex) m.set(value, p);
let pp = v.get(value)||'';
let path = p.replace(/undefined\.\.?/,'');
let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
!init ? (init=value) : (val===init ? val="#REF:$" : 0);
if(!pp && isComplex) v.set(value, path);
return val;
}
}
// ---------------
// TEST
// ---------------
// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2: a }, b, a }; // duplicate reference
a.a3 = [1,2,b]; // circular reference
b.b3 = a; // circular reference
let s = JSON.stringify(obj, refReplacer(), 4);
console.log(s);
BONUS: and here is inverse function of such serialisation
function parseRefJSON(json) {
let objToPath = new Map();
let pathToObj = new Map();
let o = JSON.parse(json);
let traverse = (parent, field) => {
let obj = parent;
let path = '#REF:$';
if (field !== undefined) {
obj = parent[field];
path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
}
objToPath.set(obj, path);
pathToObj.set(path, obj);
let ref = pathToObj.get(obj);
if (ref) parent[field] = ref;
for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
}
traverse(o);
return o;
}
// ------------
// TEST
// ------------
let s = `{
"o1": {
"o2": {
"a1": 1,
"a2": 2,
"a3": [
1,
2,
{
"b1": 3,
"b2": "4",
"b3": "#REF:$.o1.o2"
}
]
}
},
"b": "#REF:$.o1.o2.a3[2]",
"a": "#REF:$.o1.o2"
}`;
console.log('Open Chrome console to see nested fields:');
let obj = parseRefJSON(s);
console.log(obj);
/*
This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
Params:
obj - your object
inc_ident - can be " " or "\t".
show_types - show types of object or not
ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
var res = "";
if (!ident)
ident = "";
if (typeof(obj) == "string") {
res += "\"" + obj + "\" ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
res += obj;
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (obj instanceof Array) {
res += "[ ";
res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var new_ident = ident + inc_ident;
var arr = [];
for(var key in obj) {
arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "]";
} else {
var new_ident = ident + inc_ident;
res += "{ ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var arr = [];
for(var key in obj) {
arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "}\r\n";
}
return res;
};
example to use:
var obj = {
str : "hello",
arr : ["1", "2", "3", 4],
b : true,
vobj : {
str : "hello2"
}
}
var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();
f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();
your_object1.txt:
{
"str" : "hello" ,
"arr" : [
"1" ,
"2" ,
"3" ,
4
],
"b" : true,
"vobj" : {
"str" : "hello2"
}
}
your_object2.txt:
{ /* typeobj: object*/
"str" : "hello" /* typeobj: string*/,
"arr" : [ /* typeobj: object*/
"1" /* typeobj: string*/,
"2" /* typeobj: string*/,
"3" /* typeobj: string*/,
4/* typeobj: number*/
],
"b" : true/* typeobj: boolean*/,
"vobj" : { /* typeobj: object*/
"str" : "hello2" /* typeobj: string*/
}
}
For your example, I think
console.log("Item:",o)
would be easiest. But,
console.log("Item:" + o.toString)
would also work.
Using method number one uses a nice dropdown in the console, so a long object would work nicely.
I hope this example will help for all those who all are working on array of objects
var data_array = [{
"id": "0",
"store": "ABC"
},{
"id":"1",
"store":"XYZ"
}];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
If you wont aplay join() to Object.
const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
arr.push(obj[p]);
const str = arr.join(',');
I have an object:
{"f":{"cid":"325","field_name[10][0]":"133","field_name[10][1]":"132","price":"320|3600"}}
And I would like to convert this object to query string.
I'm using this function:
function toQueryString(obj, prefix) {
var str = [];
for(var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
toQueryString(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
}
But this function gives me result:
f[cid]=325&f[field_name[10][0]]=133&f[field_name[10][1]]=132&f[price]=320%7C3600
This is wrong as I can't get right result on my server side:
Array
(
[f] => Array
(
[cid] => 325
[field_name[10] => Array
(
[0] => 133
)
[price] => 320|3600
)
)
How can I solve this problem?
I think the right result will be something like this:
f[cid]=325&f[field_name[[10][0]]]=133&f[field_name[[10][1]]]=132&f[price]=320%7C3600
I changed your function a little in order to correct the nested query strings:
function toQueryString(obj, prefix) {
var str = [], k, v;
for(var p in obj) {
if (!obj.hasOwnProperty(p)) {continue;} // skip things from the prototype
if (~p.indexOf('[')) {
k = prefix ? prefix + "[" + p.substring(0, p.indexOf('[')) + "]" + p.substring(p.indexOf('[')) : p;
// only put whatever is before the bracket into new brackets; append the rest
} else {
k = prefix ? prefix + "[" + p + "]" : p;
}
v = obj[p];
str.push(typeof v == "object" ?
toQueryString(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
}
Running this function on your original object now gives us this query string:
f[cid]=325&f[field_name][10][0]=133&f[field_name][10][1]=132&f[price]=320|3600
If we pass this to a PHP page told to print_r($_GET), it gives us:
Array
(
[f] => Array
(
[cid] => 325
[field_name] => Array
(
[10] => Array
(
[0] => 133
[1] => 132
)
)
[price] => 320|3600
)
)
Exactly what you wanted, right?
This question already has an answer that does what you want, but I decided to explain the alternative that I hinted at in my comment because I think it is good to know more than one way of doing things.
It doesn't do what you want exactly, but I think it is a simpler, robuster, and more maintainable method of transmitting arbitrary objects.
function toQueryString(obj, name) {
return encodeURIComponent(name) + '=' +
encodeURIComponent(JSON.stringify(obj));
}
On the php side (assuming name was "foo"), all you have to do is:
$foo=json_decode($_GET["foo"], true);
The only bit of difficulty is that if you want to support certain versions of Internet Explorer, you have to use a polyfill for JSON.stringify, but these are readily available.
The drawback is naturally an extra indirection, but I think there is a major benefit: you are pushing the burden of bug testing this to the browser manufacturers and (if necessary) the developers of whatever implementation of JSON.stringify you decide to use.
Granted that has the drawback of introducing a new dependency, but I believe it is useful enough to warrant it.
Your mileage may vary.
Also: if you can send the data using a POST request, than you can directly send the result of JSON.stringify as raw POST data without URL encoding it. In the PHP side you can fetch it with json_decode(file_get_contents("php://input"), true)
I just wrote this. It works for me.
let objToQueryString = function (obj, prefix) {
let fields = [];
if (obj && Object.keys(obj).length) {
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof obj[i] === 'object') {
fields.push(objToQueryString(obj[i], prefix ? prefix + '[' + i + ']' : i));
} else {
fields.push((prefix ? prefix + '[' + i + ']' : i) + '=' + (typeof obj[i] === 'undefined' ? '' : encodeURIComponent(obj[i])));
}
}
}
} else if (prefix) {
fields.push(prefix + '=');
}
return fields.join('&');
};
objToQueryString({x: 1, y: 2, z: {a: 10, b: 20, c: {i: 100, j: null, k: {}}}}); //returns "x=1&y=2&z[a]=10&z[b]=20&z[c][i]=100&z[c][j]=&z[c][k]="
Enjoy.
TypeScript
declare global {
interface Object {
queryString: () => string;
}
}
if (!Object.prototype.queryString) {
Object.defineProperty(Object.prototype, 'queryString', {
value: function () {
var parts = [];
let obj = this;
for (var key in obj) {
if (typeof obj[key] == 'object') {
for (var key2 in obj[key]) {
parts.push(`${encodeURIComponent(key)}[${encodeURIComponent(key2)}]` + '=' + encodeURIComponent(obj[key][key2]));
}
} else if (typeof obj[key] == 'string') {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return "?" + parts.join('&');
}
});
}
input: {"test":{"convert":"querystring"}}
output: test[convert]=querystring
function solution(inputString, objectName)
{
var startingIndex = inputString.replace(/'/g, "").indexOf('{')
var endingIndex = inputString.replace(/'/g, "").indexOf('}')
var propertyValuePairs = inputString.replace(/'/g, "").substring(startingIndex + 1, endingIndex ).split(',')
var propertyValues = new Array();
$.each(propertyValuePairs , function(index, element){
var elements = element.split(':'); propertyValues.push({property: elements[0], value: elements[1]});
});
var result = "";
for (var i = 0; i < propertyValues.length; i++) {
result += objectName + "[" + propertyValues[i].property + "]" + "=" + propertyValues[i].value + "&";
}
return result.substring(0, result.length - 1);
}
I realize that fundamentally I'm probably going about this the wrong way so I'm open to any pushes in the right direction.
I'm trying to use the HipChat API to send a notification to a room like so:
https://www.hipchat.com/docs/api/method/rooms/message
I'm trying to build the URL in the example with a js object's parameters, so basically I'm trying to convert this:
var hipChatSettings = {
format:"json",
auth_token:token,
room_id: 1,
from: "Notifications",
message: "Message"
}
To this:
https://api.hipchat.com/v1/rooms/message?format=json&auth_token=token&room_id=1&from=Notifications&message=Message
You should check this jQuery.param function.
var params = { width:1680, height:1050 };
var str = jQuery.param( params );
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Object.keys(hipChatSettings).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(hipChatSettings[k]);
}).join('&')
// => "format=json&auth_token=token&room_id=1&from=Notifications&message=Message"
Warning: newish JavaScript. If you want it to work on ancients, shim or rewrite into for.
Something like this could work for you
var str = "?" + Object.keys(hipChatSettings).map(function(prop) {
return [prop, hipChatSettings[prop]].map(encodeURIComponent).join("=");
}).join("&");
// "?format=json&auth_token=token&room_id=1&from=Notifications&message=Message"
If you can't depend on ECMAScript 5, you can use a simple for loop
var pairs = [];
for (var prop in hipChatSettings) {
if (hipChatSettings.hasOwnProperty(prop)) {
var k = encodeURIComponent(prop),
v = encodeURIComponent(hipChatSettings[prop]);
pairs.push( k + "=" + v);
}
}
var str = "?" + pairs.join("&");
ES6 version, can do really nested objects with arrays
encodeURI(getUrlString({a: 1, b: [true, 12.3, "string"]}))
getUrlString (params, keys = [], isArray = false) {
const p = Object.keys(params).map(key => {
let val = params[key]
if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
if (Array.isArray(params)) {
keys.push("")
} else {
keys.push(key)
}
return getUrlString(val, keys, Array.isArray(val))
} else {
let tKey = key
if (keys.length > 0) {
const tKeys = isArray ? keys : [...keys, key]
tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
}
if (isArray) {
return `${ tKey }[]=${ val }`
} else {
return `${ tKey }=${ val }`
}
}
}).join('&')
keys.pop()
return p
}
Late to the dance but I quite enjoyed the brevity of this:
Object.entries(hipChatSettings)
.map(
([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
)
.join("&");
How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Most modern browsers support this method natively, but for those that don't, you can include a JS version.
Use javascript String() function
String(yourobject); //returns [object Object]
or stringify()
JSON.stringify(yourobject)
Sure, to convert an object into a string, you either have to use your own method, such as:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (Object.prototype.hasOwnProperty.call(obj, p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604
or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.
Update:
A more modern solution would be:
function objToString (obj) {
let str = '';
for (const [p, val] of Object.entries(obj)) {
str += `${p}::${val}\n`;
}
return str;
}
or:
function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
Keeping it simple with console, you can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console.
Example:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
Output:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
One option:
console.log('Item: ' + JSON.stringify(o));
Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:
console.log('Item: ', o);
None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.
I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.
//Make an object a string that evaluates to an equivalent object
// Note that eval() seems tricky and sometimes you have to do
// something like eval("a = " + yourString), then use the value
// of a.
//
// Also this leaves extra commas after everything, but JavaScript
// ignores them.
function convertToText(obj) {
//create an array that will later be joined into a string.
var string = [];
//is object
// Both arrays and objects seem to return "object"
// when typeof(obj) is applied to them. So instead
// I am checking to see if they have the property
// join, which normal objects don't have but
// arrays do.
if (typeof(obj) == "object" && (obj.join == undefined)) {
string.push("{");
for (prop in obj) {
string.push(prop, ": ", convertToText(obj[prop]), ",");
};
string.push("}");
//is array
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
string.push("[")
for(prop in obj) {
string.push(convertToText(obj[prop]), ",");
}
string.push("]")
//is function
} else if (typeof(obj) == "function") {
string.push(obj.toString())
//all other values can be done with JSON.stringify
} else {
string.push(JSON.stringify(obj))
}
return string.join("")
}
EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:
Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.
Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.
If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.
In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.
For example the following would convert all items in "value" to a string:
$.each(this, function (name, value) {
alert(String(value));
});
More details here:
http://www.w3schools.com/jsref/jsref_string.asp
I was looking for this, and wrote a deep recursive one with indentation :
function objToString(obj, ndeep) {
if(obj == null){ return String(obj); }
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return '{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray];
default: return obj.toString();
}
}
Usage : objToString({ a: 1, b: { c: "test" } })
var obj={
name:'xyz',
Address:'123, Somestreet'
}
var convertedString=JSON.stringify(obj)
console.log("literal object is",obj ,typeof obj);
console.log("converted string :",convertedString);
console.log(" convertedString type:",typeof convertedString);
There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:
console.log('Item: %o', o);
I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).
If you just want to see the object for debugging, you can use
var o = {a:1, b:2}
console.dir(o)
1.
JSON.stringify(o);
Item: {"a":"1", "b":"2"}
2.
var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);
Item: {a:1, b:2}
It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});
JSON methods are quite inferior to the Gecko engine .toSource() primitive.
See the SO article response for comparison tests.
Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).
(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)
javascript:
Object.prototype.spoof=function(){
if (this instanceof String){
return '(new String("'+this.replace(/"/g, '\\"')+'"))';
}
var str=(this instanceof Array)
? '['
: (this instanceof Object)
? '{'
: '(';
for (var i in this){
if (this[i] != Object.prototype.spoof) {
if (this instanceof Array == false) {
str+=(i.match(/\W/))
? '"'+i.replace('"', '\\"')+'":'
: i+':';
}
if (typeof this[i] == 'string'){
str+='"'+this[i].replace('"', '\\"');
}
else if (this[i] instanceof Date){
str+='new Date("'+this[i].toGMTString()+'")';
}
else if (this[i] instanceof Array || this[i] instanceof Object){
str+=this[i].spoof();
}
else {
str+=this[i];
}
str+=', ';
}
};
str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
(this instanceof Array)
? ']'
: (this instanceof Object)
? '}'
: ')'
);
return str;
};
for(i in objRA=[
[ 'Simple Raw Object source code:',
'[new Array, new Object, new Boolean, new Number, ' +
'new String, new RegExp, new Function, new Date]' ] ,
[ 'Literal Instances source code:',
'[ [], {}, true, 1, "", /./, function(){}, new Date() ]' ] ,
[ 'some predefined entities:',
'[JSON, Math, null, Infinity, NaN, ' +
'void(0), Function, Array, Object, undefined]' ]
])
alert([
'\n\n\ntesting:',objRA[i][0],objRA[i][1],
'\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
'\ntoSource() spoof:',obj.spoof()
].join('\n'));
which displays:
testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
new RegExp, new Function, new Date]
.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
/(?:)/, (function anonymous() {}), (new Date(1303248037722))]
toSource() spoof:
[[], {}, {}, {}, (new String("")),
{}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]
and
testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]
.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]
toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]
and
testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]
.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
function Function() {[native code]}, function Array() {[native code]},
function Object() {[native code]}, (void 0)]
toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]
For non-nested objects:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
stringify-object is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object
npm install stringify-object
then:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Obviously it's interesting only if you have circular object that would fail with JSON.stringify();
As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj) :
function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
If you only care about strings, objects, and arrays:
function objectToString (obj) {
var str = '';
var i=0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(typeof obj[key] == 'object')
{
if(obj[key] instanceof Array)
{
str+= key + ' : [ ';
for(var j=0;j<obj[key].length;j++)
{
if(typeof obj[key][j]=='object') {
str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
}
else
{
str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
}
}
str+= ']' + (i > 0 ? ',' : '')
}
else
{
str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
}
}
else {
str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
}
i++;
}
}
return str;
}
maybe you are looking for
JSON.stringify(JSON.stringify(obj))
"{\"id\":30}"
Take a look at the jQuery-JSON plugin
At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.
If you can use lodash you can do it this way:
> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'
With lodash map() you can iterate over Objects as well.
This maps every key/value entry to its string representation:
> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]
And join() put the array entries together.
If you can use ES6 Template String, this works also:
> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'
Please note this do not goes recursive through the Object:
> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]
Like node's util.inspect() will do:
> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
function objToString (obj) {
var str = '{';
if(typeof obj=='object')
{
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + ':' + objToString (obj[p]) + ',';
}
}
}
else
{
if(typeof obj=='string')
{
return '"'+obj+'"';
}
else
{
return obj+'';
}
}
return str.substring(0,str.length-1)+"}";
}
var o = {a:1, b:2};
o.toString=function(){
return 'a='+this.a+', b='+this.b;
};
console.log(o);
console.log('Item: ' + o);
Since Javascript v1.0 works everywhere (even IE)
this is a native approach and allows for a very costomised look of your object while debugging and in production
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
Usefull example
var Ship=function(n,x,y){
this.name = n;
this.x = x;
this.y = y;
};
Ship.prototype.toString=function(){
return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};
alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523
Also, as a bonus
function ISO8601Date(){
return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6 Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29
Circular References
By using below replacer we can produce less redundant JSON - if source object contains multi-references to some object, or contains circular references - then we reference it by special path-string (similar to JSONPath) - we use it as follows
let s = JSON.stringify(obj, refReplacer());
function refReplacer() {
let m = new Map(), v= new Map(), init = null;
return function(field, value) {
let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field);
let isComplex= value===Object(value)
if (isComplex) m.set(value, p);
let pp = v.get(value)||'';
let path = p.replace(/undefined\.\.?/,'');
let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
!init ? (init=value) : (val===init ? val="#REF:$" : 0);
if(!pp && isComplex) v.set(value, path);
return val;
}
}
// ---------------
// TEST
// ---------------
// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2: a }, b, a }; // duplicate reference
a.a3 = [1,2,b]; // circular reference
b.b3 = a; // circular reference
let s = JSON.stringify(obj, refReplacer(), 4);
console.log(s);
BONUS: and here is inverse function of such serialisation
function parseRefJSON(json) {
let objToPath = new Map();
let pathToObj = new Map();
let o = JSON.parse(json);
let traverse = (parent, field) => {
let obj = parent;
let path = '#REF:$';
if (field !== undefined) {
obj = parent[field];
path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
}
objToPath.set(obj, path);
pathToObj.set(path, obj);
let ref = pathToObj.get(obj);
if (ref) parent[field] = ref;
for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
}
traverse(o);
return o;
}
// ------------
// TEST
// ------------
let s = `{
"o1": {
"o2": {
"a1": 1,
"a2": 2,
"a3": [
1,
2,
{
"b1": 3,
"b2": "4",
"b3": "#REF:$.o1.o2"
}
]
}
},
"b": "#REF:$.o1.o2.a3[2]",
"a": "#REF:$.o1.o2"
}`;
console.log('Open Chrome console to see nested fields:');
let obj = parseRefJSON(s);
console.log(obj);
/*
This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
Params:
obj - your object
inc_ident - can be " " or "\t".
show_types - show types of object or not
ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
var res = "";
if (!ident)
ident = "";
if (typeof(obj) == "string") {
res += "\"" + obj + "\" ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
res += obj;
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (obj instanceof Array) {
res += "[ ";
res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var new_ident = ident + inc_ident;
var arr = [];
for(var key in obj) {
arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "]";
} else {
var new_ident = ident + inc_ident;
res += "{ ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var arr = [];
for(var key in obj) {
arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "}\r\n";
}
return res;
};
example to use:
var obj = {
str : "hello",
arr : ["1", "2", "3", 4],
b : true,
vobj : {
str : "hello2"
}
}
var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();
f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();
your_object1.txt:
{
"str" : "hello" ,
"arr" : [
"1" ,
"2" ,
"3" ,
4
],
"b" : true,
"vobj" : {
"str" : "hello2"
}
}
your_object2.txt:
{ /* typeobj: object*/
"str" : "hello" /* typeobj: string*/,
"arr" : [ /* typeobj: object*/
"1" /* typeobj: string*/,
"2" /* typeobj: string*/,
"3" /* typeobj: string*/,
4/* typeobj: number*/
],
"b" : true/* typeobj: boolean*/,
"vobj" : { /* typeobj: object*/
"str" : "hello2" /* typeobj: string*/
}
}
For your example, I think
console.log("Item:",o)
would be easiest. But,
console.log("Item:" + o.toString)
would also work.
Using method number one uses a nice dropdown in the console, so a long object would work nicely.
I hope this example will help for all those who all are working on array of objects
var data_array = [{
"id": "0",
"store": "ABC"
},{
"id":"1",
"store":"XYZ"
}];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
If you wont aplay join() to Object.
const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
arr.push(obj[p]);
const str = arr.join(',');
I'm trying to iterate over a "value" list and convert it into a string. Here is the code:
var blkstr = $.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
alert(str);
return str;
}).get().join(", ");
alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?
If value is not a plain array, such code will work fine:
var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
(output will appear in the dev console)
As Felix mentioned, each() is just iterating the array, nothing more.
Converting From Array to String is So Easy !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That's it Now A is a string. :)
You can use .toString() to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c.
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
Four methods to convert an array to a string.
Coercing to a string
var arr = ['a', 'b', 'c'] + []; // "a,b,c"
var arr = ['a', 'b', 'c'] + ''; // "a,b,c"
Calling .toString()
var arr = ['a', 'b', 'c'].toString(); // "a,b,c"
Explicitly joining using .join()
var arr = ['a', 'b', 'c'].join(); // "a,b,c" (Defaults to ',' seperator)
var arr = ['a', 'b', 'c'].join(','); // "a,b,c"
You can use other separators, for example, ', '
var arr = ['a', 'b', 'c'].join(', '); // "a, b, c"
Using JSON.stringify()
This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.
var arr = JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
jQuery.each is just looping over the array, it doesn't do anything with the return value∆. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):
var blkstr = $.map(value, function(val,index) {
var str = index + ":" + val;
return str;
}).join(", ");
DEMO
But why use jQuery at all in this case? map only introduces an unnecessary function call per element.
var values = [];
for(var i = 0, l = value.length; i < l; i++) {
values.push(i + ':' + value[i]);
}
// or if you actually have an object:
for(var id in value) {
if(value.hasOwnProperty(id)) {
values.push(id + ':' + value[id]);
}
}
var blkstr = values.join(', ');
∆: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.
this's my function, convert object or array to json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
i just edit to v0.2 ^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
OR
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
convert an array to a GET param string that can be appended to a url could be done as follows
function encodeGet(array){
return getParams = $.map(array , function(val,index) {
var str = index + "=" + escape(val);
return str;
}).join("&");
}
call this function as
var getStr = encodeGet({
search: $('input[name="search"]').val(),
location: $('input[name="location"]').val(),
dod: $('input[name="dod"]').val(),
type: $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;
which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.
Here's an example using underscore functions.
var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");
Final output would be "moe,larry,curly"
You shouldn't confuse arrays with lists.
This is a list: {...}. It has no length or other Array properties.
This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();
someObj.toString(); will not work on any other object types, like lists.