Is there a function in javascript similar to compact from php?

I found the compact function very useful (in php). Here is what he does:

 $some_var = 'value'; $ar = compact('some_var'); //now $ar is array('some_var' => 'value') 

Thus, it creates an array of variables that you specify when the key for the elements is the name of the variable. Is there any function in javascript?

+6
source share
4 answers

There is no similar function and there is no way to get the names / values โ€‹โ€‹of variables for the current context - only if they are "global" variables on the window , which is not recommended. If so, you can do this:

 function compact() { var obj = {}; Array.prototype.forEach.call(arguments, function (elem) { obj[elem] = window[elem]; }); return obj; } 
+5
source

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 browser compatibility, you can always use Babel

+3
source

You can also use phpjs library to use the same function in javascript as in php

Example

 var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld'; compact('var1', 'var2', 'var3'); 

Output

 {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'} 
+1
source

If the variables are not globally, it is still 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 that.

 var a=1,b=2; console.log({a,b}) // {a:1,b:2} 
0
source

Source: https://habr.com/ru/post/943850/


All Articles