Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 array from variables which you specify, when key for elements is variable name. Is there any kind of function in javascript ?

like image 640
kirugan Avatar asked Apr 29 '13 03:04

kirugan


People also ask

What does compact do JavaScript?

compact() function is an inbuilt function in Underscore. js library of JavaScript which is used to return an array after removing all the false values. The false values in JavaScript are NaN, undefined, false, 0, null or an empty string.

What is compact function PHP?

The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values. Syntax: array compact("variable 1", "variable 2"...)

Why Compact is used in laravel?

The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.


1 Answers

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

like image 169
Carlos B Avatar answered Nov 14 '22 21:11

Carlos B