Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function return value possible as an array key?

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

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

..

example (typically more than one pair):

var data = { encloseAttrSelector('name', 'username'):  row.first().text() };
like image 259
jn025 Avatar asked Apr 26 '26 18:04

jn025


2 Answers

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

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

The new ES2015 syntax is:

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

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

like image 117
Pointy Avatar answered Apr 28 '26 06:04

Pointy


For more than one pair, please do this:

var data = {};
data[encloseAttrSelector('name', 'username')] = row.first().text();
like image 33
Praveen Kumar Purushothaman Avatar answered Apr 28 '26 06:04

Praveen Kumar Purushothaman