with texto numero number convertir convert javascript string object tostring

javascript - texto - Convertir un objeto en una cadena



string javascript (29)

¿Cómo puedo convertir un objeto JavaScript en una cadena?

Ejemplo:

var o = {a:1, b:2} console.log(o) console.log(''Item: '' + o)

Salida:

Objeto {a = 1, b = 2} // salida legible muy agradable :)
Elemento: [objeto Objeto] // ni idea de lo que hay dentro :(


1.

JSON.stringify(o);

Elemento: {"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);

Artículo: {a: 1, b: 2}


Claro, para convertir un objeto en una cadena, debes usar tu propio método, como:

function objToString (obj) { var str = ''''; for (var p in obj) { if (obj.hasOwnProperty(p)) { str += p + ''::'' + obj[p] + ''/n''; } } return str; }

En realidad, lo anterior solo muestra el enfoque general; es posible que desee utilizar algo como http://phpjs.org/functions/var_export:578 o http://phpjs.org/functions/var_dump:604

o, si no está utilizando métodos (funciona como propiedades de su objeto), es posible que pueda usar el nuevo estándar (pero no implementado en navegadores más antiguos, aunque también puede encontrar una utilidad que lo ayude), JSON .stringify (). Pero, de nuevo, eso no funcionará si el objeto utiliza funciones u otras propiedades que no son serializables a JSON.


Como Firefox no encorda algún objeto como objeto de pantalla; si desea obtener el mismo resultado, como: 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('','')+''}''; }


En los casos en que sabe que el objeto es solo un Booleano, Fecha, Cadena, número, etc. La función Cadena () de javascript funciona bien. Recientemente encontré esto útil para tratar con los valores provenientes de la función $ .each de jquery.

Por ejemplo, lo siguiente convertiría todos los artículos en "valor" a una cadena:

$.each(this, function (name, value) { alert(String(value)); });

Más detalles aquí:

http://www.w3schools.com/jsref/jsref_string.asp


Espero que este ejemplo ayude a todos aquellos que están trabajando en una variedad de objetos.

var data_array = [{ "id": "0", "store": "ABC" },{ "id":"1", "store":"XYZ" }]; console.log(String(data_array[1]["id"]+data_array[1]["store"]));


Estaba buscando esto, y escribí una profunda recursiva con sangría:

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

Uso: objToString({ a: 1, b: { c: "test" } })


Los métodos JSON son bastante inferiores al motor Gecko primitivo .toSource ().

Vea la respuesta del artículo SO para las pruebas de comparación.

Además, la respuesta anterior se refiere a http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html que, como JSON, (que el otro artículo http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json utiliza a través de "Código fuente de codificación JSON de ExtJs" ) no puede manejar referencias circulares y está incompleto. El código a continuación muestra sus limitaciones (falsificadas) (corregidas para manejar matrices y objetos sin contenido).

( enlace directo al código en //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''));

que muestra:

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")]

y

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")]

y

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]


Manteniéndolo simple con la console , puedes usar una coma en lugar de un + . El + intentará convertir el objeto en una cadena, mientras que la coma lo mostrará por separado en la consola.

Ejemplo:

var o = {a:1, b:2}; console.log(o); console.log(''Item: '' + o); console.log(''Item: '', o); // :)

Salida:

Object { a=1, b=2} // useful Item: [object Object] // not useful Item: Object {a: 1, b: 2} // Best of both worlds! :)

Referencia: https://developer.mozilla.org/en-US/docs/Web/API/Console.log


Ninguna de las soluciones aquí funcionó para mí. JSON.stringify parece ser lo que dice mucha gente, pero corta funciones y parece bastante roto para algunos objetos y matrices que probé al probarlo.

Hice mi propia solución que funciona en Chrome al menos. Publicándolo aquí para que cualquiera que busque esto en Google pueda encontrarlo.

//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: Sé que este código puede mejorarse pero nunca pude hacerlo. El usuario andrey sugirió una mejora here con el comentario:

Aquí hay un pequeño código modificado, que puede manejar ''nulo'' e ''indefinido'', y también no agrega comas excesivas.

Úsalo bajo tu propio riesgo ya que no lo he verificado en absoluto. Siéntase libre de sugerir cualquier mejora adicional como un comentario.


Para objetos no anidados:

Object.entries(o).map(x=>x.join(":")).join("/r/n")


Para su ejemplo, creo que console.log("Item:",o) sería más fácil. Pero, console.log("Item:" + o.toString) también funcionaría.

El uso del método número uno utiliza un buen menú desplegable en la consola, por lo que un objeto largo funcionaría bien.


Recomendaría usar JSON.stringify , que convierte el conjunto de variables en el objeto en una cadena JSON. La mayoría de los navegadores modernos admiten este método de forma nativa, pero para aquellos que no lo hacen, puede incluir una versión JS :

var obj = { name: ''myObj'' }; JSON.stringify(obj);


Si desea un método minimalista para convertir una variable en una cadena para una situación de tipo de expresión en línea, ''''+variablename es el mejor juego de golf.

Si ''variablename'' es un objeto y usa la operación de concatenación de cadenas vacías, dará el molesto [object Object] , en cuyo caso probablemente desee la respuesta JSON.stringify Gary C. enormemente votada a la pregunta publicada, que puede leer acerca de la Red de Desarrolladores de Mozilla en el enlace en esa respuesta en la parte superior .


Si está utilizando el marco javascript de Dojo, ya existe una función de compilación para hacer esto: dojo.toJson () que se usaría como tal.

var obj = { name: ''myObj'' }; dojo.toJson(obj);

que devolverá una cadena. Si desea convertir el objeto a datos json, agregue un segundo parámetro de verdadero.

dojo.toJson(obj, true);

http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson


Si no quieres jugar 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('','');


Si puedes usar lodash puedes hacerlo de esta manera:

> var o = {a:1, b:2}; > ''{'' + _.map(o, (value, key) => key + '':'' + value).join('', '') + ''}'' ''{a:1, b:2}''

Con el map() lodash map() puedes iterar sobre los objetos también. Esto mapea cada entrada clave / valor a su representación de cadena:

> _.map(o, (value, key) => key + '':'' + value) [ ''a:1'', ''b:2'' ]

Y join() las entradas de la matriz.

Si puedes usar ES6 Template String, esto también funciona:

> `{${_.map(o, (value, key) => `${key}:${value}`).join('', '')}}` ''{a:1, b:2}''

Tenga en cuenta que esto no es recursivo a través del Objeto:

> var o = {a:1, b:{c:2}} > _.map(o, (value, key) => `${key}:${value}`) [ ''a:1'', ''b:[object Object]'' ]

Como util.inspect() del nodo hará:

> util.inspect(o) ''{ a: 1, b: { c: 2 } }''


Si solo desea ver el objeto para la depuración, puede utilizar

var o = {a:1, b:2} console.dir(o)


Si solo estás enviando a la consola, puedes usar console.log(''string:'', obj) . Note la coma .


Si solo te interesan las cadenas, los objetos y las matrices:

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


Usa la función String () de javascript.

String(yourobject); //returns [object Object]

o

JSON.stringify(yourobject)

.


stringify-object es una buena biblioteca de npm realizada por el equipo de yeoman: https://www.npmjs.com/package/stringify-object

npm install stringify-object

entonces:

const stringifyObject = require(''stringify-object''); stringifyObject(myCircularObject);

Obviamente, es interesante solo si tiene un objeto circular que podría fallar con JSON.stringify();


EDITAR No use esta respuesta ya que no funciona en Internet Explorer. Usa la solución de Gary Chambers .

toSource() es la función que está buscando que la escribirá como JSON.

var object = {}; object.first = "test"; object.second = "test2"; alert(object.toSource());


Echa un vistazo al complemento jQuery-JSON

En su núcleo, utiliza JSON.stringify pero recurre a su propio analizador si el navegador no lo implementa.


Una opción :

console.log(''Item: '' + JSON.stringify(o));

Otra opción (como soktinpk señaló en los comentarios), y mejor para la depuración de la consola IMO:

console.log(''Item: '', o);


/* 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; };

ejemplo a utilizar:

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

su_objeto1.txt:

{ "str" : "hello" , "arr" : [ "1" , "2" , "3" , 4 ], "b" : true, "vobj" : { "str" : "hello2" } }

tu_objeto2.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*/ } }


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)+"}"; }


setobjToString:function(obj){ var me =this; obj=obj[0]; var tabjson=[]; for (var p in obj) { if (obj.hasOwnProperty(p)) { if (obj[p] instanceof Array){ tabjson.push(''"''+p +''"''+ '':'' + me.setobjToString(obj[p])); }else{ tabjson.push(''"''+p +''"''+'':"''+obj[p]+''"''); } } } tabjson.push() return ''{''+tabjson.join('','')+''}''; }


var o = {a:1, b:2}; o.toString=function(){ return ''a=''+this.a+'', b=''+this.b; }; console.log(o); console.log(''Item: '' + o);

Dado que Javascript v1.0 funciona en todas partes (incluso en IE), este es un enfoque nativo y permite un aspecto muy personalizado de su objeto durante la depuración y en la producción https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Ejemplo util

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

Además, como bonificación

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


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