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 have a project that requires me to convert an Object to a string, without using stringify. The aim of this is to implement a recursive function that converts an object to a string. I seem to be having 2 problems here:
1) My function to output the Object as a string, only seems to be outputting the first value, not the rest.
function myToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
str += val + " : " + argObj[val] + "\n";
console.log(str);
}
return str;
}
}
2) My understanding of the above for in loop, would be that it would print each key/value pair in the object, but it is only doing so for the first key/value. Using recursion, how can I get this to run over each key/value pair.
You had your return value inside the for loop, meaning it returned on the first iteration through it. Try this:
function myToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
str += val + " : " + argObj[val] + "\n";
document.write(str);
}
}
return str;
}
After that you want to know if any of the properties of argObj are objects so you can recursively call the function on any of them. From this SO post grab a function to test if a variable is an object. You probably do not want to include arrays in your recursive call. You probably want to print their contents. (but that is another question hey) Then your code becomes something like this:
function myAndSomeGuyOnStackOverflowToString(argObj) {
var str = "";
for (var val in argObj) {
if (argObj.hasOwnProperty(val)) {
var propertyValue = argObj[val];
if (isAnObject(propertyValue)){
propertyValue = myAndSomeGuyOnStackOverflowToString(propertyValue)
}
str += val + " : " + propertyValue + "\n";
document.write(str);
}
}
return str;
}
function isAnObject(objArg){
//choose your implementation from the many on that other post I mentioned
}
And with some indentation and string formatting you should be well on your way.
function myToString(argObj, res) {
if ( argObj !== null && typeof argObj === "object") {
for (var val in argObj)
res += val + " : " + argObj[val] + "\n";
}
if (typeof argObj === "number" || typeof argObj === "string")
return res + argObj;
return res;
}
Invoke this function by calling myToString(object, ""), it returns a string. Hope it can help you or give you some idea to write it recursively.
I have a nested JSON object given by
var data = {
"animal":
{
"canine": "dog",
"feline": "cat"
},
"bug": "beetle",
"carrot":
{
"color": "orange",
"type": "vegetable"
},
"population": 100
};
I have been trying to use JSON.stringify to store this information by
localStorage.setItem("myData", JSON.stringify(data));
but it does not store the nested parts of the JSON object. For example, it ignores it and instead shows
"animal":{}
How might I simply be able to resolve this issue? I have seen solutions involving modifying ajax to become synchronous, but I didn't really understand what was happening.
I just want it so that I can obtain in console
console.log(JSON.stringify(data))
//{"animal":{"canine":"dog","feline":"cat"},"bug":"beetle","carrot":{"color":"orange","type":"vegetable"},"population":100}
so if there is a method that does not use stringify, that will be great too.
I created a solution that worked for me.
I wrote a recursive function that uses a preorder algorithm through the object. It is not complete, obvious improvements could be made to make it more generic (especially with arrays of objects, or things like that), but it works on a basic level quite well I find.
function recursiveObjStr(obj, str)
{
str += "{";
for(var inst in obj)
{
str += "\"" + inst + "\"" + ":";
if(isArray(obj[inst]))
{
str += "[";
for(var inst2 in obj[inst])
{
str += "\"" + obj[inst][inst2] + "\"" + ",";
}
str = str.substring(0,str.length-1);
str += "]";
}
else if(typeof(obj[inst]) == "object")
{
str = recursiveObjStr(obj[inst], str);
}
else if(typeof(obj[inst]) == "function")
{
str += obj[inst];
}
else
{
if(!(isNaN(obj[inst])))
{
str += obj[inst];
}
else if(typeof(obj[inst]) == "boolean")
{
str += obj[inst];
}
else
{
str += "\"" + obj[inst] + "\"";
}
}
if(str[str.length-1] !== ",")
{
str += ",";
}
}
str = str.substring(0, str.length - 1);
str += "},";
return str;
}
Using this isArray() function taken from https://stackoverflow.com/a/218833/4309934
function isArray ( obj ) {
return isObject(obj) && (obj instanceof Array);
}
There is an issue with having an additional comma at the end, so to remove it I use substring again. For example, with data defined as in the original question, it can be used by
var str = "";
str = recursiveObjStr(data, str);
//console.log(str) gives {"animal":{"canine":"dog","feline":"cat"},"bug":"beetle","carrot":{"color":"orange","type":"vegetable"},"population":100},
str = str.substring(0, str.length-1);
//removes the comma
Feel free to find improvements to this method.
I am enumerating through the properties of an object. It works fine when I set the object directly.
I need to use prompt (class assignment) to allow the user to input an object name. The problem is obj returns as a string
How can I cast the value from the prompt to an object?
function enumObject(){
var obj;
var propertyName;
obj = prompt("Please enter an object name","window.navigator");
obj = window.navigator;
if (typeof obj == "object"){
for (propertyName in obj){
document.write(propertyName + " : " + obj[propertyName] + "<br>");
}
}
else {
alert('The object name is undefined.');
}
obj = null;
propertyName = null;
}
enumObject();
An object name...?!?
Do you want your user to inform a global variable name which refers an object?
If so, you could do:
var name = prompt("Enter a global variable name.");
var obj = window[name];
If you want your user to enter a string which will be converted to an object literal, you could do:
var objDef = prompt("Enter a string representing an object");
var obj = eval("(function(){return " + objDef + ";})()");
or...
var objDef = prompt("Enter a string representing an object");
var obj = new Function("return " + objDef)();
If you want to access a object variable in a function scope and you're not using "strict mode", try:
(function(){
var someObj = { b:123, c: 321 };
var name = prompt("Enter an object variable name in local scope.");//Here, your user could enter "someObj"
eval("console.log(" + name + ")");
})();
I would suggest:
function enumObject(){
var obj;
var propertyName;
obj = prompt("Please enter an object name","window.navigator");
window[obj] = {};
if (typeof window[obj] == "object"){
for (propertyName in obj){
document.write(propertyName + " : " + obj[propertyName] + "<br>");
}
}
else {
alert('The object name is undefined.');
}
}
enumObject();
I need to use prompt (class assignment) to allow the user to input an
object name. The problem is obj returns as a string
How can I cast the value from the prompt to an object?
You can't since Objects don't have names. You can have either variables or object properties whose value is a reference to an object though:
var obj = {};
creates a variable whose name is obj and whose value is a reference to an object.
If you want to dynamically create variables, you can use eval, but it's not recommended. It is very much warned against to use eval to execute random code entered by users since they are completely unaware of the variables that already exist and that you don't want them to mess with.
What you can do is create an object specifically to add properties to, since almost any string value can be used as a property name. So you might do:
function enumObject(){
// markup and div will be used later
var markup = '';
var div;
// Here's where the property names will be stored
var obj = {};
var propertyName = prompt("Please enter an object name", "window.navigator");
obj[propertyName] = {};
// This is redundant since an object was just assigned so it will
// always return true
if (typeof obj[propertyName] == "object") {
// Always perform a hasOwnProperty check so you don't get
// inherited properties, you only want the ones added by the user
// Also, don't re-used variables, create a new one
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// Don't use document.write after the page has finished loading
// as it will clear the entire document first before writing
markup += propertyName + " : " + obj[propertyName] + "<br>";
}
}
// This should never execute since the test should always be true
} else {
alert('The object name is undefined.');
}
// Write to the document without destroying it
div = document.createElement('div');
div.innerHTML = markup;
document.body.appendChild(div);
}
Edit
Maybe you want to access object properties based on user defined strings. In that case, you can do something like the following. It only uses eval if the root of the property accessor is not window and only strings that appear to be valid identifiers, not random code:
// Assumes dot notation like window.navigator or foo.bar
function getObjectValueByString(s) {
var identifier, path = [];
// Very simple identifier re
var identifierRe = /^[_$a-z][a-z0-9_$]*$/i;
s = s.split('.');
// Loop over parts of s
for (var i=0, iLen=s.length; i<iLen; i++) {
identifier = s[i];
path.push(identifier);
if (identifierRe.test(identifier)) {
// Get root of accessor
if (i == 0) {
if (identifier == 'window') {
obj = window;
// Only use eval on what appear to be valid identifiers
// not arbitrary code
} else {
obj = eval(identifier);
}
// If not root, get property value
} else {
obj = obj[identifier];
}
// Stop if obj isn't an object
if (typeof obj != 'object') {
// Message if didn't get to end of accessor
if (i < iLen - 1) {
return 'Stopped at ' + path.join('.') + ' = ' + obj;
}
}
} else {
return identifier + ' is not a valid identifier';
}
}
return path.join('.') + ' = ' + obj;
}
To play with it:
<input onblur="console.log(getObjectValueByString(this.value));">
A much more rigorous regular expression for identifier names that excludes reserved words is in the accepted answer for Valid Characters for JavaScript Variable Names.
If only properties of window are required, life becomes much simpler and eval is not needed at all, so nor is the regular expression to check for valid identifiers:
function getWindowValueByString(s) {
var identifier, path = [];
var obj = window;
s = s.split('.');
// Loop over parts of s
for (var i=0, iLen=s.length; i<iLen; i++) {
identifier = s[i];
path.push(identifier);
// Check only using window
if (i == 0) {
if (identifier != 'window') {
return 'Only valid for properties of window';
}
} else {
obj = obj[identifier];
}
// Stop if obj isn't an object
if (typeof obj != 'object') {
// Message if didn't get to end of accessor
if (i < iLen - 1) {
return 'Stopped at ' + path.join('.') + ' = ' + obj;
}
}
}
return path.join('.') + ' = ' + obj;
}
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);
}