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

后端 未结 4 614
醉梦人生
醉梦人生 2021-01-18 15:24

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         


        
相关标签:
4条回答
  • 2021-01-18 15:58

    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

    0 讨论(0)
  • 2021-01-18 16:00

    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}
    
    0 讨论(0)
  • 2021-01-18 16:05

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

    Example

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

    Output

    {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'}
    
    0 讨论(0)
  • 2021-01-18 16:07

    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;
    }
    
    0 讨论(0)
提交回复
热议问题