Is the return value function possible as an array key?

I made a lazy utility function that I wanted to pass as my array, but I was getting syntax errors, is it possible to pass a function inside an array as a key?

function encloseAttrSelector(attr, value)
{
    return '[' + attr + '="' + value + '"]';
}   

      

..

Example

(usually more than one pair):

var data = { encloseAttrSelector('name', 'username'):  row.first().text() };

      

+3


source to share


2 answers


In ES6 ES2015 (the newest official standard for the language) yes, but in most real-world contexts, no. However, you can do this:

var data = {};
data[encloseAttrSelector('name', 'username')] = row.first().text();

      

New ES2015 syntax:



var data = { [encloseAttrSelector('name', 'username')] : row.first().text() };

      

That is, the square brackets around what would normally be just a property name in an object initializer expression. Any expression can be inside the square brackets.

+6


source


For more than one pair, please do the following:



var data = {};
data[encloseAttrSelector('name', 'username')] = row.first().text();

      

+2


source







All Articles