Related
We need to see what methods/fields an object has in Javascript.
As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.
If Firebug isn't an option for you, then try this simple script:
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".
If you are using firefox then the firebug plug-in console is an excellent way of examining objects
console.debug(myObject);
Alternatively you can loop through the properties (including methods) like this:
for (property in object) {
// do what you want with property, object[property].value
}
A lot of modern browsers support the following syntax:
JSON.stringify(myVar);
It can't be stated enough that you can use console.debug(object) for this. This technique will save you literally hundreds of hours a year if you do this for a living :p
To answer the question from the context of the title of this question, here is a function that does something similar to a PHP var_dump. It only dumps one variable per call, but it indicates the data type as well as the value and it iterates through array's and objects [even if they are Arrays of Objects and vice versa]. I'm sure this can be improved on. I'm more of a PHP guy.
/**
* Does a PHP var_dump'ish behavior. It only dumps one variable per call. The
* first parameter is the variable, and the second parameter is an optional
* name. This can be the variable name [makes it easier to distinguish between
* numerious calls to this function], but any string value can be passed.
*
* #param mixed var_value - the variable to be dumped
* #param string var_name - ideally the name of the variable, which will be used
* to label the dump. If this argumment is omitted, then the dump will
* display without a label.
* #param boolean - annonymous third parameter.
* On TRUE publishes the result to the DOM document body.
* On FALSE a string is returned.
* Default is TRUE.
* #returns string|inserts Dom Object in the BODY element.
*/
function my_dump (var_value, var_name)
{
// Check for a third argument and if one exists, capture it's value, else
// default to TRUE. When the third argument is true, this function
// publishes the result to the document body, else, it outputs a string.
// The third argument is intend for use by recursive calls within this
// function, but there is no reason why it couldn't be used in other ways.
var is_publish_to_body = typeof arguments[2] === 'undefined' ? true:arguments[2];
// Check for a fourth argument and if one exists, add three to it and
// use it to indent the out block by that many characters. This argument is
// not intended to be used by any other than the recursive call.
var indent_by = typeof arguments[3] === 'undefined' ? 0:arguments[3]+3;
var do_boolean = function (v)
{
return 'Boolean(1) '+(v?'TRUE':'FALSE');
};
var do_number = function(v)
{
var num_digits = (''+v).length;
return 'Number('+num_digits+') '+v;
};
var do_string = function(v)
{
var num_chars = v.length;
return 'String('+num_chars+') "'+v+'"';
};
var do_object = function(v)
{
if (v === null)
{
return "NULL(0)";
}
var out = '';
var num_elem = 0;
var indent = '';
if (v instanceof Array)
{
num_elem = v.length;
for (var d=0; d<indent_by; ++d)
{
indent += ' ';
}
out = "Array("+num_elem+") \n"+(indent.length === 0?'':'|'+indent+'')+"(";
for (var i=0; i<num_elem; ++i)
{
out += "\n"+(indent.length === 0?'':'|'+indent)+"| ["+i+"] = "+my_dump(v[i],'',false,indent_by);
}
out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
return out;
}
else if (v instanceof Object)
{
for (var d=0; d<indent_by; ++d)
{
indent += ' ';
}
out = "Object \n"+(indent.length === 0?'':'|'+indent+'')+"(";
for (var p in v)
{
out += "\n"+(indent.length === 0?'':'|'+indent)+"| ["+p+"] = "+my_dump(v[p],'',false,indent_by);
}
out += "\n"+(indent.length === 0?'':'|'+indent+'')+")";
return out;
}
else
{
return 'Unknown Object Type!';
}
};
// Makes it easier, later on, to switch behaviors based on existance or
// absence of a var_name parameter. By converting 'undefined' to 'empty
// string', the length greater than zero test can be applied in all cases.
var_name = typeof var_name === 'undefined' ? '':var_name;
var out = '';
var v_name = '';
switch (typeof var_value)
{
case "boolean":
v_name = var_name.length > 0 ? var_name + ' = ':''; // Turns labeling on if var_name present, else no label
out += v_name + do_boolean(var_value);
break;
case "number":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + do_number(var_value);
break;
case "string":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + do_string(var_value);
break;
case "object":
v_name = var_name.length > 0 ? var_name + ' => ':'';
out += v_name + do_object(var_value);
break;
case "function":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + "Function";
break;
case "undefined":
v_name = var_name.length > 0 ? var_name + ' = ':'';
out += v_name + "Undefined";
break;
default:
out += v_name + ' is unknown type!';
}
// Using indent_by to filter out recursive calls, so this only happens on the
// primary call [i.e. at the end of the algorithm]
if (is_publish_to_body && indent_by === 0)
{
var div_dump = document.getElementById('div_dump');
if (!div_dump)
{
div_dump = document.createElement('div');
div_dump.id = 'div_dump';
var style_dump = document.getElementsByTagName("style")[0];
if (!style_dump)
{
var head = document.getElementsByTagName("head")[0];
style_dump = document.createElement("style");
head.appendChild(style_dump);
}
// Thank you Tim Down [http://stackoverflow.com/users/96100/tim-down]
// for the following addRule function
var addRule;
if (typeof document.styleSheets != "undefined" && document.styleSheets) {
addRule = function(selector, rule) {
var styleSheets = document.styleSheets, styleSheet;
if (styleSheets && styleSheets.length) {
styleSheet = styleSheets[styleSheets.length - 1];
if (styleSheet.addRule) {
styleSheet.addRule(selector, rule)
} else if (typeof styleSheet.cssText == "string") {
styleSheet.cssText = selector + " {" + rule + "}";
} else if (styleSheet.insertRule && styleSheet.cssRules) {
styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
}
}
};
} else {
addRule = function(selector, rule, el, doc) {
el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
};
}
// Ensure the dump text will be visible under all conditions [i.e. always
// black text against a white background].
addRule('#div_dump', 'background-color:white', style_dump, document);
addRule('#div_dump', 'color:black', style_dump, document);
addRule('#div_dump', 'padding:15px', style_dump, document);
style_dump = null;
}
var pre_dump = document.getElementById('pre_dump');
if (!pre_dump)
{
pre_dump = document.createElement('pre');
pre_dump.id = 'pre_dump';
pre_dump.innerHTML = out+"\n";
div_dump.appendChild(pre_dump);
document.body.appendChild(div_dump);
}
else
{
pre_dump.innerHTML += out+"\n";
}
}
else
{
return out;
}
}
You want to see the entire object (all nested levels of objects and variables inside it) in JSON form. JSON stands for JavaScript Object Notation, and printing out a JSON string of your object is a good equivalent of var_dump (to get a string representation of a JavaScript object). Fortunately, JSON is very easy to use in code, and the JSON data format is also pretty human-readable.
Example:
var objectInStringFormat = JSON.stringify(someObject);
alert(objectInStringFormat);
console.dir (toward the bottom of the linked page) in either firebug or the google-chrome web-inspector will output an interactive listing of an object's properties.
See also this Stack-O answer
If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.
A bit of improvement on nickf's function for those that don't know the type of the variable coming in:
function dump(v) {
switch (typeof v) {
case "object":
for (var i in v) {
console.log(i+":"+v[i]);
}
break;
default: //number, string, boolean, null, undefined
console.log(typeof v+":"+v);
break;
}
}
I improved nickf's answer, so it recursively loops through objects:
function var_dump(obj, element)
{
var logMsg = objToString(obj, 0);
if (element) // set innerHTML to logMsg
{
var pre = document.createElement('pre');
pre.innerHTML = logMsg;
element.innerHTML = '';
element.appendChild(pre);
}
else // write logMsg to the console
{
console.log(logMsg);
}
}
function objToString(obj, level)
{
var out = '';
for (var i in obj)
{
for (loop = level; loop > 0; loop--)
{
out += " ";
}
if (obj[i] instanceof Object)
{
out += i + " (Object):\n";
out += objToString(obj[i], level + 1);
}
else
{
out += i + ": " + obj[i] + "\n";
}
}
return out;
}
console.log(OBJECT|ARRAY|STRING|...);
console.info(OBJECT|ARRAY|STRING|...);
console.debug(OBJECT|ARRAY|STRING|...);
console.warn(OBJECT|ARRAY|STRING|...);
console.assert(Condition, 'Message if false');
These Should work correctly On Google Chrome and Mozilla Firefox (if you are running with old version of firefox, so you have to install Firebug plugin)
On Internet Explorer 8 or higher you must do as follow:
Launch "Developer Tools, by clicking on F12 Button
On the Tab List, click on "Script" Tab"
Click on "Console" Button in the right side
For more informations you can visit this URL: https://developer.chrome.com/devtools/docs/console-api
You can simply use the NPM package var_dump
npm install var_dump --save-dev
Usage:
const var_dump = require('var_dump')
var variable = {
'data': {
'users': {
'id': 12,
'friends': [{
'id': 1,
'name': 'John Doe'
}]
}
}
}
// print the variable using var_dump
var_dump(variable)
This will print:
object(1) {
["data"] => object(1) {
["users"] => object(2) {
["id"] => number(12)
["friends"] => array(1) {
[0] => object(2) {
["id"] => number(1)
["name"] => string(8) "John Doe"
}
}
}
}
}
Link: https://www.npmjs.com/package/#smartankur4u/vardump
Thank me later!
If you are looking for PHP function converted in JS, there is this little site: http://phpjs.org.
On there you can get most of the PHP function reliably written in JS. for var_dump try: http://phpjs.org/functions/var_dump/ (make sure to check the top comment, this depends on "echo", which can also be downloaded from the same site)
I used the first answer, but I felt was missing a recursion in it.
The result was this:
function dump(obj) {
var out = '';
for (var i in obj) {
if(typeof obj[i] === 'object'){
dump(obj[i]);
}else{
out += i + ": " + obj[i] + "\n";
}
}
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
Based on previous functions found in this post.
Added recursive mode and indentation.
function dump(v, s) {
s = s || 1;
var t = '';
switch (typeof v) {
case "object":
t += "\n";
for (var i in v) {
t += Array(s).join(" ")+i+": ";
t += dump(v[i], s+3);
}
break;
default: //number, string, boolean, null, undefined
t += v+" ("+typeof v+")\n";
break;
}
return t;
}
Example
var a = {
b: 1,
c: {
d:1,
e:2,
d:3,
c: {
d:1,
e:2,
d:3
}
}
};
var d = dump(a);
console.log(d);
document.getElementById("#dump").innerHTML = "<pre>" + d + "</pre>";
Result
b: 1 (number)
c:
d: 3 (number)
e: 2 (number)
c:
d: 3 (number)
e: 2 (number)
Here is my solution. It replicates the behavior of var_dump well, and allows for nested objects/arrays. Note that it does not support multiple arguments.
function var_dump(variable) {
let out = "";
let type = typeof variable;
if(type == "object") {
var realType;
var length;
if(variable instanceof Array) {
realType = "array";
length = variable.length;
} else {
realType = "object";
length = Object.keys(variable).length;
}
out = `${realType}(${length}) {`;
for (const [key, value] of Object.entries(variable)) {
out += `\n [${key}]=>\n ${var_dump(value).replace(/\n/g, "\n ")}\n`;
}
out += "}";
} else if(type == "string") {
out = `${type}(${type.length}) "${variable}"`;
} else {
out = `${type}(${variable.toString()})`;
}
return out;
}
console.log(var_dump(1.5));
console.log(var_dump("Hello!"));
console.log(var_dump([]));
console.log(var_dump([1,2,3,[1,2]]));
console.log(var_dump({"a":"b"}));
Late to the game, but here's a really handy function that is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP
Note, you can use tags as well by passing 'TAG-YourTag' and it will be applied until another tag is read, for example, 'TAG-YourNextTag'
/*
* Brief: Print to console.log() from PHP
* Description: Print as many strings,arrays, objects, and other data types to console.log from PHP.
* To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
* you can pass as many data as you want an this will still work.
*
* This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*
* A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
* detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
* be applied to all data after it.
*
* Example:
* consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3);
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
$tag = substr($arg,4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('".$tag." ".$arg."');</script>";
}
}
}
}
NOTE: func_num_args() and func_num_args() are php functions for reading a dynamic number of input args, and allow this function to have infinitely many console.log requests from one function call
The following is my favorite var_dump/print_r equivalent in Javascript to PHPs var_dump.
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
I just want to add something relatively important about console.log
If you are debugging large variables (like large audio or video data buffers). When you print console.log(big_variable) the console will only display a small part of it. (it seems a bit obvious).
If however, the variable is in a loop and this variable is constantly changing, if you ever "copy it into your clipboard" , what the browser will do is to ask for the variable AGAIN (and that may have changed by the time you are copying).
I'll tell you my story. I am programming an app that deals with big chunks of audio data, with Float32arrays of size 8192. If the buffer had certain characteristics, I would print the variable using console.log() and then grab that variable to test and toy around and play with it (and even use it for mocks so I can do automated testing)
However, the results would never hold. The mic would capture the audio data, store it on a this.audioBuffer variable and the whole thing would work, but when I copied that exact variable from console.log so I could us it as a mock to run some automated tests, the behaviour would change dramatically.
It took me a while to figure this out, Apparently, whenever i "copied" or "set the variable as global" in the debugger, rather than copying the variables displayed in console.log, the jsvm would ask for the this.audioBuffer again. and since the variable was being used inside of a loop, the microphone would still record and I would get a completely different sound array than what I was listening to and thought the audio buffer was in the first place.
If you are dealing with large complex data structures like audio or video files, image files... and these are subject to change when you are reading the values in the chrome /firefox / edge console, make sure you don't console.log(variable), but rather console.log(JSON.stringify(variable)). it will save you a ton of time
you can use this for strings and objects/array
function print_r(obj){
return JSON.stringify(obj, null, "\t");
}
I am working on a learning project that requires me to implement a recursive function that stringifies a passed in object, without using JSON.stringify. I have to consider all data types as parameters that my function will receive, and while I am fine with that, I seem to be getting confused when an array/object is passed, and I call the function on itself to iterate over the object contents.
I am not doing it right and every change I make is impacting other areas I thought I had completed so my frustration is starting to win this battle. Areas I need help on:
Output all elements of an array/object in the same way as JSON.stringify when I call the function on itself. An example of an issue I see is, if I pass an array like ["SO"], I am am getting [SO] returned, but it looks like I have that possibility covered!
What to do when a function is passed as a param, which is not allowed.
Here is what I have so far. I appreciate any help you can offer.
var myJSONRecursiveFunc = function (obj) {
var stringed = "";
var result;
if (Number.isInteger(obj)) {
return "" + obj + "";
} else if (obj === null) {
return "" + null + "";
} else if (typeof obj === "boolean") {
return "" + obj + "";
} else if (typeof obj === "string") {
return '"' + obj + '"';
} else if (Array.isArray(obj)) {
if (obj.length === 0) {
return "[" + obj + "]";
}
for (var i = 0; i < obj.length; i++) {
if (Array.isArray(i)) {
myJSONRecursiveFunc(i);
} else {
stringed += "" + obj[i] + ""
}
}
return result = "[" + stringed + "]";
} else {
for (var val in obj) {
if (typeof val === "object") {
myJSONRecursiveFunc(val);
}
stringed += "" + val + "" + ":" + "" + obj[val] + "" + '';
}
return result = "{" + stringed + "}";
}
};
It is far from perfect as I am still learning so please let me know where I can improve along with any help in getting this to work as is.
Output all elements of an array/object in the same way as JSON.stringify when I call the function on itself. An example of an issue I see is, if I pass an array like ["SO"], I am am getting [SO] returned, but it looks like I have that possibility covered!
Your recursion of var val in obj is only passing in val, which is the key of obj. You need to call myJSONRecursiveFunc(obj[val]) in order to get the right result. Additionally, this is true for your array. Your if statement needs to check to see if obj[i] is an array, not i which would just be an integer. In this case, you need to say:
if (Array.isArray(obj[i])) {
myJSONRecursiveFunc(obj[i])
}
What to do when a function is passed as a param, which is not allowed.
You would need to have a check to see if the function being passed in is a function, with typeof, such as: if (typeof func === function)
This is a pretty fun exercise. I did this a few months back, and had access to the Underscore library to do so. Here's working code:
var stringifyJSON = function(obj) {
//Strings and null should be addressed here. Strings have quotes inside the string so I can't lump them together with booleans and numbers.
if (_.isString(obj)){
return '"' + obj.split('"').join('\\"') + '"';
}
if (_.isNull(obj)){
return 'null';
}
//Arrays get a temporary array that their stringified elements get pushed to, and then that temporary array is joined together and concatenated with the brackets that exist within the returned string.
if (_.isArray(obj)){
var tempArr = [];
_.each(obj, function(elem){
tempArr.push(stringifyJSON(elem));
});
return '[' + tempArr.join(',') + ']';
}
//Objects get a temporary string to add their stringified data to. Including a check for undefined values and function keys.
if (_.isObject(obj)){
var tempArr = [];
for (var k in obj){
if (_.isUndefined(obj[k]) || _.isFunction(k)){
return '{}';
} else {
tempArr.push(stringifyJSON(k) + ':' + stringifyJSON(obj[k]));
}
}
return '{' + tempArr.join(', ') + '}';
}
//Everything else = booleans, numbers
else {
return obj.toString();
}
};
Okay, let's do this.
Annotated suggestions
function toJSON(obj) {
// There are people who will disagree with me
// but I think this variable is declared way too early.
// It's used in 2 places as a temp variable, so should
// be declared closer to where it's used.
// It should also be named more appropriately for how it's used.
// I used `arrayParts` and `keyValuePairs` instead.
var stringed = "";
// As far as I can tell, this variable is never actually
// used for anything useful.
// It's always `return result = <thing>`.
// If you're immediately returning, there's no need to save
// to a variable.
var result;
if (Number.isInteger(obj)) {
// The initial `"" + <number>` converts to a string.
// Appending another "" to the end is pointless in
// all of the below lines.
return "" + obj + "";
} else if (obj === null) {
return "" + null + "";
} else if (typeof obj === "boolean") {
return "" + obj + "";
} else if (typeof obj === "string") {
return '"' + obj + '"';
} else if (Array.isArray(obj)) {
// If the object is an array with length 0, you
// already know what it looks like.
// It's `[]`, so just return that instead of adding
// the empty array in the middle.
if (obj.length === 0) {
return "[" + obj + "]";
}
for (var i = 0; i < obj.length; i++) {
// In the top of this function, you handle all the
// different types of objects, so you should recurse and
// reuse that logic. Checking again here is wasted effort.
if (Array.isArray(i)) {
myJSONRecursiveFunc(i);
} else {
stringed += "" + obj[i] + ""
}
}
return result = "[" + stringed + "]";
// A better way to write this section would have
// looked like this.
// var arrayParts = []
// for( var i = 0; i < obj.length; i++ ){
// var stringifiedElement = toJSON( obj[ i ] )
// arrayParts.push( stringifiedElement )
// }
// return '[' + arrayParts.join( ',' ) + ']'
} else {
for (var val in obj) {
// Again, your function's start checks type and handles it.
// Use that recursively.
if (typeof val === "object") {
myJSONRecursiveFunc(val);
}
stringed += "" + val + "" + ":" + "" + obj[val] + "" + '';
}
return result = "{" + stringed + "}";
// This section could be rewritten as:
// var keyValuePairs = []
// for( var key in obj ){
// var pair = '"' + key + '":' + toJSON( obj[ key ] )
// keyValuePairs.push( pair )
// }
// return '{' + keyValuePairs.join( ',' ) + '}'
}
};
Your error
For the record, when you pass in ['SO'] into your function, this is what is happening. The isArray block catches the object first.
} else if( Array.isArray( obj ) ){
Then inside your loop, the else block returns "" + obj[i] + "", which converts to "" + "SO" + "", which turns into "SO".
When this is returned, "[" + "SO" + "]" turns into "[SO]".
for (var i = 0; i < obj.length; i++) {
if (Array.isArray(i)) {
myJSONRecursiveFunc(i);
} else {
stringed += "" + obj[i] + "" // <-- the error
}
}
Additional Suggestions
When you loop over obj as an actual object near the end, you do so like this.
for( var val in obj ){
// foo
}
Sidenote: val is actually the key, so that's a bit misleading.
This is an ugly part of Javascript. If the raw Object is modified, for example: Object.prototype.foobar = 5, then 'foobar':5 will show up in every object in your program. It's worth noting that only developers who are very sure what they are doing should ever be doing this, but it is possible.
To make sure this does not break your program, add the following code.
for( var key in obj ){
if( ! obj.hasOwnProperty( key ) ){
continue
}
}
obj.hasOwnProperty( <name> ) checks if obj has a direct property <name>. If it does not, then we skip to the next loop iteration with continue.
I have a JavaScript function what is dig through on object and make a string value to function object.
Have this JSON:
{
"active": true,
"icons": {
"activeHeader": "ui-icon-alert"
},
"animate": {
"duration": 1000, "always": "dMethod"
}
}
I use JSON.parse on this string so I reach options.animate.always as a string with value dMethdod which is actually a name of the method. So I can access this through window[options.animate.always] and I wish to change the options.animate.always from string to method that is pointed to the string.
I make a function for this job:
function SetFunctions(options, functionName) {
var path = functionName.split(".");
var setterObject = options;
for (var k = 0; k < path.length; k++) {
if (setterObject != undefined) {
setterObject = setterObject[path[k]];
} else {
break;
}
}
if (setterObject != undefined && window[setterObject] != undefined) {
setterObject = window[setterObject];
}
}
I call this function with the variable returned from the parse and function name animate.always as value.
The part that find the correct property is worked, but when I set the value of the setterObject the change is not affect the original value.
I'm thinking to build up the reference as string 'options.animate.always = dMethod' and use eval on it, but I really want to avoid using eval function (I know eval is evil :)).
FINAL SOULUTION:
I put answers together and finished my method. Finally become two methods. I comment it and share maybe useful to others:
function ChangeStringToFunction(functionPath, rootObject, separator) {
// functionPath is required parameter
if (functionPath === undefined || functionPath === null) return;
// rootObject is optional. If not supplied the window object will be the base of the search
var localRootObject = rootObject === undefined ? window : rootObject;
// separator is optional. If not supplied the '.' will be the separator
var localSeparator = separator === undefined ? "." : separator;
// split the string reference (example "jui.someObj1.someOjb2"
var pathParts = functionPath.split(localSeparator);
var currentObject = localRootObject;
// exclude the last part
for (var i = 0; i < pathParts.length - 1; i++) {
currentObject = currentObject[pathParts[i]];
// it's useless to go forward if there is no object
if (currentObject === undefined) return;
}
// get the string represent the name of the function (full path could be included)
var currentValue = currentObject[pathParts[pathParts.length - 1]];
// the value must be a string
if (typeof currentValue !== "string") return;
// get the function reference based on the value provided
var functionReference = ResolveFunction(currentValue);
// if the result is not a function it's meaningless to continue
if (typeof functionReference !== "function") return;
// and finally change the string value of the object with the function value represent by our string
currentObject[pathParts[pathParts.length - 1]] = functionReference;
}
function ResolveFunction(functionPath, separator, rootObject) {
if (functionPath === undefined || functionPath === null) return undefined;
var localRootObject = rootObject === undefined ? window : rootObject;
var localSeparator = separator === undefined ? "." : separator;
var pathParts = functionPath.split(localSeparator);
var currentObject = localRootObject;
for (var i = 0; i < pathParts.length; i++) {
currentObject = currentObject[pathParts[i]];
if (currentObject === undefined) break;
}
return typeof currentObject === "function" ? currentObject : undefined;
}
but when I set the value of the setterObject the change is not affect the original value.
Yes, you are only assigning to a variable. That will never change anything else but the variable, since JavaScript does not have pointers.
To change an object, you will have to assign to a property. In your case, you will have to omit the last iteration to get the object which you then assign to:
function SetFunctions(options, functionName) {
var path = functionName.split("."),
setterObject = options;
for (var k=0; setterObject!=null && k<path.length-1; k++) {
setterObject = setterObject[path[k]];
}
var prop = path[k],
fn = setterObject!=null && window[setterObject[prop]];
if (fn) {
setterObject[prop] = fn;
}
}
Btw, I think in your case it might be easier to build a CallFunctions function that directly invokes the function with the name stored in that property, instead of replacing the property value with the method - unless you plan to invoke it very often.
It depends on the level of indirection you want.
If the method will always be called "always", you can do something like this:
function SetFunction(object, propertyName, functionName) {
var functionObj = window[functionName];
object[propertyName] = functionObj;
}
And call it like this:
SetFunction(myObj.animate, "always", myObj.animate.always);
But I suspect you want something a bit more generic?
Let's say that I want to search for a value, like 'StackOverflow', in all declared variables in window.
I can do it with this code:
function globalSearch(obj, value) {
for(var p in obj)
if(obj[p] == value)
return(p);
}
globalSearch(window, 'StackOverflow');
This code will return the name of a variable that have this value (or returns nothing).
So, if I have declared a variable with value 'StackOverflow', it will successfully find it.
My problem is that I want to go deeper and search thru window's objects (and its own nested objects) too, to achieve a result like this:
var x = 'StackOverflow' // returns 'x'
var y = { a : 'StackOverflow' } // returns 'y.a'
var z = { a : { b: 'StackOverflow' } } // returns 'z.a.b'
I'm having problems with inherited methods of Objects. Is there a way to do this?
Deep search but without the recursive function calls
Functional recursion has internal stack limits and wastes memory.
Additional features added
Recursive object protection in the form of a searched array; It doesn't use up too much memory of course as the objects are only stored as references.
Return true if the the object itself matches the value. Otherwise it would return '' which would match to false.
Arrays use angle-bracket notation.
The code
function globalSearch(startObject, value) {
var stack = [[startObject,'']];
var searched = [];
var found = false;
var isArray = function(test) {
return Object.prototype.toString.call( test ) === '[object Array]';
}
while(stack.length) {
var fromStack = stack.pop();
var obj = fromStack[0];
var address = fromStack[1];
if( typeof obj == typeof value && obj == value) {
var found = address;
break;
}else if(typeof obj == "object" && searched.indexOf(obj) == -1){
if ( isArray(obj) ) {
var prefix = '[';
var postfix = ']';
}else {
var prefix = '.';
var postfix = '';
}
for( i in obj ) {
stack.push( [ obj[i], address + prefix + i + postfix ] );
}
searched.push(obj);
}
}
return found == '' ? true : found;
}
Problems
Without passing the initial variable name into the function, we can't return the fully qualified variable name from the beginning. I can't think of a solution and I would be surprised if there was one.
Variable names with spaces are valid as the key to an object, as are other invalid variable names, it just means that the value must be addressed using angle-brackets. There are a couple of solutions I can think of. Regex check each variable name to make sure it's valid and use angle-brackets notation if it is not. The overriding problem with this is that the reg-ex is a page long. Alternatively, we could only use angle-brackets but this isn't really true to the OPs original question.
The indexOf call on the array 'searched' might be a bit heavy on very large objects but I can't yet think of an alternative.
Improvements
Apart from cleaning up the code a little, it would also be nice if the function returned an array of matches. This also raises another issue in that the returned array would not contain references to recursive objects. Maybe the function could accept a result format configuration parameter.
This should work. It uses recursion to achieve the result.
function globalSearch(obj, value) {
for(var p in obj)
if(obj[p] == value){
return(p);
}else if(typeof obj[p] == "object" && obj[p] != obj){
var te = globalSearch(obj[p], value);
if(te!=false){ return p + "." + te }
}
return false;
}
Make your solution recursive. If you have an object, call your function again.
function globalSearch(obj, value) {
for(var p in obj) {
if (obj[p] == value) {
return(p);
} else if (typeof obj[p] === "object") {
var recursiveCheck= globalSearch(obj[p], value);
if (recursiveCheck) {
return p + "." + recursiveCheck;
}
}
}
}
globalSearch(window, 'StackOverflow');
I bet most browsers will hit a warning for too much looping.
This code, based on the other answer, allows for all possible value matches to be found.
function globalSearch(startObject, value, returnFirstResult = false) {
var stack = [[startObject,'']];
var searched = [];
var found = new Set();
var isArray = function(test) {
return Object.prototype.toString.call( test ) === '[object Array]';
}
while(stack.length) {
var fromStack = stack.pop();
var obj = fromStack[0];
var address = fromStack[1];
if( typeof obj == typeof value && obj == value) {
if (returnFirstResult) {
return address == '' ? false : address;
}
found.add(address)
}if(typeof obj == "object" && searched.indexOf(obj) == -1){
if ( isArray(obj) ) {
var prefix = '[';
var postfix = ']';
}else {
var prefix = '.';
var postfix = '';
}
for( i in obj ) {
stack.push( [ obj[i], address + prefix + i + postfix ] );
}
searched.push(obj);
}
}
return Array.from(found);
}
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the dest variable in JavaScript?
Here is a fast and easy way of parsing query strings in JavaScript:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
console.log(getQueryVariable('x'));
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2 into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
You can also use the excellent URI.js library by Rodney Rehm. Here's how:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...
'use strict';
function parseQuery(search) {
var args = search.substring(1).split('&');
var argsParsed = {};
var i, arg, kvp, key, value;
for (i=0; i < args.length; i++) {
arg = args[i];
if (-1 === arg.indexOf('=')) {
argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {
kvp = arg.split('=');
key = decodeURIComponent(kvp[0]).trim();
value = decodeURIComponent(kvp[1]).trim();
argsParsed[key] = value;
}
}
return argsParsed;
}
parseQuery(document.location.search);
Following on from my comment to the answer #bobby posted, here is the code I would use:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
If you know that you will only have that one querystring variable you can simply do:
var dest = location.search.replace(/^.*?\=/, '');
The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:
window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
You can either call it once without any parameters and work with the window.parsedSearch object, or call getSearch subsequently.
I haven't fully tested this, the regular expression might still need some tweaking...
How about this?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..then just call it with:
alert('Var "dest" = ' + getQueryVar('dest'));
Cheers
I wanted a simple function that took a URL as an input and returned a map of the query params.
If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
This should work back and for with the jQuery.param( qparams ) function.
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page
Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">