admin管理员组文章数量:1332389
All:
I want to build a string from a JS object( like build a toString method but like operator overload), for example:
var info = {name:"username",age:20};
var fmtinfo = info.join("||");
the fmtinfo will be a string with format:
"name(username)||age(20)"
I wonder if anyone can give me a simple way to do that?
Thanks
All:
I want to build a string from a JS object( like build a toString method but like operator overload), for example:
var info = {name:"username",age:20};
var fmtinfo = info.join("||");
the fmtinfo will be a string with format:
"name(username)||age(20)"
I wonder if anyone can give me a simple way to do that?
Thanks
Share asked Feb 18, 2015 at 16:51 KuanKuan 11.4k25 gold badges101 silver badges212 bronze badges 2-
So you want to define
info.join
? – Ry- ♦ Commented Feb 18, 2015 at 16:52 - @minitech Any method is weled, as lone as it is simple to use. – Kuan Commented Feb 18, 2015 at 17:01
5 Answers
Reset to default 4To avoid any explicit iteration, you can use Object.keys
with map
to transform each key into the corresponding entry, then simply join
them together:
function fancyString(obj) {
return Object.keys(obj).map(function (k) {
return "" + k + "(" + obj[k] + ")";
}).join("||");
}
var foo = {name: "username", age: 20};
console.log(fancyString(foo));
To offer some explanation of how this work:
The call to Object.keys()
returns an array of the object's own enumerable keys, effectively bining the for (f in o)
and o.hasOwnProperty()
checks. Object.keys
is relatively well-supported, by everything except IE9 (although polyfills are not plicated).
That array of keys are transformed via Array.prototype.map()
, using the desired string formatting. This is pretty simple, but do not that obj[k]
will call its .toString()
method (if available) to transform it into a string. This allows excellent handling of custom objects, as you can simply define a toString
method on each and it will be picked up by the VM. Again, this is supported by IE9 and better, but polyfills are trivial.
Finally, we join the resulting strings with Array.prototype.join()
, which takes care of making sure we don't append the separator to the end or anything like that. All browsers support this.
For curiosity, the ES6 equivalent would be:
let fancyString = o => Object.keys(o).map(k => "" + k + "(" + o[k] + ")").join("||");
You can use for..in
statement and helper array:
var info = {name:"username",age:20};
var helperArray = [];
for( var key in info ) {
if( info.hasOwnProperty( key ) ) {
helperArray.push( key + '(' + info[key] + ')' );
}
}
alert(helperArray.join('||'));
You could iterate over the object's keys to get both the key names and their corresponding values. Not incredibly elegant but since the desired format of your string is unmon, it requires a little work.
var info = {name:"username",age:20};
var keys = Object.keys(info);
var returnVal = ""
for(var i = 0; i < keys.length; i++) {
if(returnVal.length > 0)
returnVal += "||";
returnVal += keys[i] + "(" + info[keys[i]] + ")";
}
alert(returnVal)
Here is a jsfiddle of the solution: http://jsfiddle/pstricker/ec1oohsk/
It took a while, but I might have got it working as intended with help of two existing Stackoverflow answers related to: Object iteration and checking if JavaScript variable is function type. I hope this helps :-)
Object.prototype.join = function join(param) {
var helperArray = []
for (var key in this) {
//check that function is not printed -> join: function
if (typeof (this[key]) != "function")
helperArray.push(key + "(" + this[key] + ")")
}
return helperArray.join(param);
}
var info = {
name: "username",
age: 20
};
console.log(info.join('||'));
console.log(info.join('<>'));
console.log(info.join('%'));
Object.prototype.fancyString = function(){
var a = []
for(var prop in this) {
if(this.hasOwnProperty(prop)) {
a.push(prop + '(' + this[prop] + ')' );
}
}
return a.join('||');
}
Then you can just do:
var info = {name:"username",age:20};
info.fancyString();
// outputs: "name(username)||age(20)"
本文标签: What is the simplest way to Join a object as a space separated string in JavascriptStack Overflow
版权声明:本文标题:What is the simplest way to Join a object as a space separated string in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742286780a2447070.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论