Kuan
Kuan

Reputation: 11389

What is the simplest way to Join a object as a space separated string in Javascript

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

Upvotes: 3

Views: 2159

Answers (5)

ssube
ssube

Reputation: 48257

To 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 combining the for (f in o) and o.hasOwnProperty() checks. Object.keys is relatively well-supported, by everything except IE9 (although polyfills are not complicated).

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

Upvotes: 4

jyrkim
jyrkim

Reputation: 2869

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

Upvotes: 1

pstricker
pstricker

Reputation: 692

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 uncommon, 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.net/pstricker/ec1oohsk/

Upvotes: 2

Chris Charles
Chris Charles

Reputation: 4446

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

Upvotes: 0

antyrat
antyrat

Reputation: 27765

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

Upvotes: 3

Related Questions