Skip to content Skip to sidebar Skip to footer

Is There A Function In Javascript Similar To Compact From Php?

I found compact function very useful (in php). Here is what it does: $some_var = 'value'; $ar = compact('some_var'); //now $ar is array('some_var' => 'value') So it create arr

Solution 1:

You can use ES6/ES2015 Object initializer

Example:

let bar = 'bar', foo = 'foo', baz = 'baz'; // declare variableslet obj = {bar, foo, baz}; // use object initializerconsole.log(obj);

{bar: 'bar', foo: 'foo', baz: 'baz'} // output

Beware of browsers compatibilities, you always can use Babel

Solution 2:

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:

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

Solution 3:

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'}

Solution 4:

If the variables are not in global scope it is still kinda possible but not practical.

functionsomefunc() {
    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}

Post a Comment for "Is There A Function In Javascript Similar To Compact From Php?"