0

I have the following javascript code:

var date = record.get('Date'),
    day = date.getDate(),
    month = date.getMonth(),
    year = date.getFullYear();

var formattedDate = year + '-' + month + '-' + day;

datePicker.selectedDates = {
    formattedDate: formattedDate
};

The result of selectedDates right now is: formattedDate: '2014-7-27'

And I need the result to be '2014-7-27' : '2014-7-27'

Any clue?

2 Answers 2

1

There is currently no syntax to do:

var key = "foo", val = "bar";
var obj = {
  [key]: val // syntax error
}

You can do this:

var key = "foo", val = "bar";
var obj = {};
obj[key] = val;

You can consider writing a function to delegate the boilerplating. I'm not sure what API would be best, maybe this:

var obj = build_object(key, val, key2, val2, ...);

ES6 gives us enhanced object literals: http://maximilianhoffmann.com/posts/object-based-javascript-in-es6 , it's still not quite what you need.

var a = "a", b = "b";
var obj = { a, b, func() {
  return "foo"
} } // { a: "a", b: "b", "func": function () { .. } }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use square bracket syntax to add dynamic key properties to the object.

datePicker.selectedDates = {}
datePicker.selectedDates[formattedDate] = formattedDate;

Comments

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.