I found compact
function very useful (in php). Here is what it does:
$some_var = \'value\';
$ar = compact(\'some_var\');
//now $ar is array(\'so
You can use ES6/ES2015 Object initializer
Example:
let bar = 'bar', foo = 'foo', baz = 'baz'; // declare variables
let obj = {bar, foo, baz}; // use object initializer
console.log(obj);
{bar: 'bar', foo: 'foo', baz: 'baz'} // output
Beware of browsers compatibilities, you always can use Babel
If the variables are not in global scope it is still kinda possible but not practical.
function somefunc() {
var a = 'aaa',
b = 'bbb';
var compact = function() {
var obj = {};
for (var i = 0; i < arguments.length; i++) {
var key = arguments[i];
var value = eval(key);
obj[key] = value;
}
return obj;
}
console.log(compact('a', 'b')) // {a:'aaa',b:'bbb'}
}
The good news is ES6 has a new feature that will do just this.
var a=1,b=2;
console.log({a,b}) // {a:1,b:2}
You can also use phpjs library for using the same function in javascript same as in php
var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld';
compact('var1', 'var2', 'var3');
{'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'}
No there is no analogous function nor is there any way to get variable names/values for the current context -- only if they are "global" variables on window
, which is not recommended. If they are, you could do this:
function compact() {
var obj = {};
Array.prototype.forEach.call(arguments, function (elem) {
obj[elem] = window[elem];
});
return obj;
}