JavaScript compact
Creates a hash containing variables and their values
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 | function compact ( ) { // Creates a hash containing variables and their values // // version: 909.322 // discuss at: http://phpjs.org/functions/compact // + original by: Waldo Malqui Silva // + tweaked by: Jack // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld'; // * example 1: compact('var1', 'var2', 'var3'); // * returns 1: {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'} var matrix = {}, that = this; var process = function ( value ) { var i = 0, l = value.length, key_value = ''; for (i = 0; i < l; i++) { key_value = value [ i ]; if (key_value instanceof Array) { process( key_value ); } else { if (typeof that.window[key_value] !== 'undefined') { matrix[key_value] = that.window[key_value]; } } } return true; }; process(arguments); return matrix; } |
Examples
Running
1 2 | var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld'; compact('var1', 'var2', 'var3'); |
Should return
1 | {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'} |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have compact goodness in JavaScript.
This version is not recursive as it should be acc to the php manual. Try run following example (taken from the manual, too):
1
2
3
4
56
7
8
9
| var city = "San Francisco"; var state = "CA"; var event = "SIGGRAPH"; var location_vars = new Array("city", "state"); var result = compact("event", "nothing_here", "location_vars"); console.log(result) |
What you get is an object with event property and location_vars property which is an Array. What should be returned is a 'flat' object with event, city and state properties (because location_vars) should be searched inside.



Brett Zamir
3 Dec '08
1 2 3 4 56 7