UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

79 lines (67 loc) 2.43 kB
--- layout: page title: "JavaScript compact function" comments: true sharing: true footer: true alias: - /functions/view/compact:371 - /functions/view/compact - /functions/view/371 - /functions/compact:371 - /functions/371 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's compact {% codeblock array/compact.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/compact.js raw on github %} function compact () { // From: http://phpjs.org/functions // + 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 (Object.prototype.toString.call(key_value) === '[object 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; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/compact.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/compact.js) ### Example 1 This code {% codeblock lang:js example %} var1 = 'Kevin'; var2 = 'van'; var3 = 'Zonneveld'; compact('var1', 'var2', 'var3'); {% endcodeblock %} Should return {% codeblock lang:js returns %} {'var1': 'Kevin', 'var2': 'van', 'var3': 'Zonneveld'} {% endcodeblock %} ### Other PHP functions in the array extension {% render_partial _includes/custom/array.html %}