3
myCoolObject {
  a: 0
  b: 12
  c: 24
}

I want to concatenate a, b and c so that they look like a unique string "a-b-c" (or "0-12-24" in the example).

a, b and c will always represent numbers. Converting each one of them from int to string require a lot of code: I'd just use sprintf() if I were in PHP or C, but how can I do this in JS without using toString() for each parameter and writing too much code?

Whole code:

var pickedDate = this.getSelectedDay().year.toString() + "-" + this.getSelectedDay().month.toString() + this.getSelectedDay().day.toString();

Seriously? Isn't there any more efficient way of doing this in js?

3
  • Will the properties always be a, b and c or is there an arbitrary number of properties in each object? Commented Jun 6, 2013 at 15:15
  • nope, same data structure all the times. Commented Jun 6, 2013 at 15:15
  • Yea, I think what you have is probably the best way. You can perhaps create a toString prototype on whatever object holds this data. Commented Jun 6, 2013 at 15:17

5 Answers 5

6
var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;

EDIT:

With ES6, you can use template strings to interpolate numbers into strings:

let myCoolString = `${myCoolObject.a}-${myCoolObject.b}-${myCoolObject.c}`;

Try it:

var myCoolObject = {
  a: 0,
  b: 12,
  c: 24
};

var myCoolString = myCoolObject.a + '-' + myCoolObject.b + '-' + myCoolObject.c;

console.log(typeof myCoolString);
console.log(myCoolString);

Sign up to request clarification or add additional context in comments.

3 Comments

they're numbers: wouldn't js try to sum them?
@Saturnix Because there's a string being concatenated in between. If you just wanted to concatenate them (without characters in between), you could just use var str = "" + myCoolObject.a + myCoolObject.b + myCoolObject.c;. As soon as a string is encountered, concatenation will happen, not addition. If addition is needed, parentheses can be used
I added a jsFiddle example to demonstrate.
2

how can I do this in JS without [...] writing too much code?

If you know all of your numbers are positive, you can write even less code to achieve the same as we know JavaScript executes left-to-right.

var obj = {a: 0, b: 12, c: 24}; /* define object
String + Number = String
                  String + Number = String
                                    String + Number = String
String + Number + Number + Number     = String    */
  ''   +  obj.a + -obj.b + -obj.c; // = "0-12-24"

The - were inserted because String + -Number = "String-Number", e.g.

'AK' + -47 // "AK-47"

2 Comments

+1 I don't know why this has been downvoted - looks like a legit answer to me.
legit okay but how is anyone supposed to maintain this code? You save two quotation marks and one plus sign compared to rink's answer and in exchange readability takes a huge hit.
1

Without much code it looks perfect here is the demo

myObj = {
  a: 0,
  b: 12,
  c: 24
}; 

var r="";

// iterate through all object properties
for (var p in myObj) 
{
    //concatenate it
    r+=myObj[p]+"-";
}

//remove the last dash
r=r.substring(0,r.length-1);

alert(r.substring(0,r.length-1));

Comments

1

This is mostly done with Array.join:

var pickedDate = [
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day
].join("-")

Although I personally prefer a small utility function similar to pythonic format():

format = function(fmt /*, args */) {
    var args = [].slice.call(arguments, 1);
    return fmt.replace(/{(\d+)}/g, function($0, $1) { 
        return String(args[$1])
    })
}

and then:

var pickedDate = format('{0}-{1}-{2}', 
    this.getSelectedDay().year, 
    this.getSelectedDay().month, 
    this.getSelectedDay().day)

Comments

0
  1. Try sprintf() for JavaScript.

  2. Add new method to string

    if (!String.prototype.format) {
    String.prototype.format = function() {
       var args = arguments;
       return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
           ? args[number]
            : match
          ;
       });
      };
    }
    
    "{0} - {1} - {2}".format(myCoolObject.a, myCoolObject.b,myCoolObject.c)
    

1 Comment

Please link to the original code instead of copypasting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.