What is the equivalent of str (R language) in javascript, to get the structure of an object?

StackOverflow https://stackoverflow.com/questions/18125884

  •  23-06-2022
  •  | 
  •  

Frage

In R , we have the handy function str to inspect object that tells you the structure of an object.

Here an example used to get the structure of a parsed json object ( I am using json just to give a useful example)

txt = '{"name":"agstudy","job":"developer"}'
library(rjson)
obj = fromJSON(txt)

Now using str:

str(obj)
List of 2
$ name: chr "agstudy"
$ job : chr "developer"

Now using jquery for example I can do this for example:

txt = '{"name":"agstudy","job":"developer"}';
var obj = $.parseJSON(txt);
var x = '';
$.each(obj, function(key, val) {
    x = x + ' key ' + key + ' val ' + val +'\n'
  });

But I am looking for more handy function?

War es hilfreich?

Lösung

Basically you have two comfortable options.

Using your example object,

var obj = {name:"agstudy",job:"developer"};
console.log ("Formatted object %O",obj)
console.dir (obj);

this looks like this

  • Chrome
    • console.log
    • enter image description here
    • console.dir
    • enter image description here
  • Firefox (using firebug)
    • console.log
    • enter image description here
    • console.dir
    • enter image description here
  • ... IE flaws
    • enter image description here

Here is a Fiddle as well.

If you are looking for a way to print your objects directly in a Fiddle site, taking a look at JSBin, which provides a built-in console, is worth it.

enter image description here

Andere Tipps

Yes you are, it is called console.log or console.dir :)

var obj = $.parseJSON(txt);
console.log(obj);

Then check your console.

What is console.log and how do I use it?

as i understand str function in R have aim to informate you about things in your code via R console. So, why don't you want to use javascript console for same aim?

There is a huge ammount of console commands that can show you as more info as you want:

console.log
console.assert
console.clear
console.count
console.debug
console.dir
console.dirxml
console.error
console.exception
console.group
console.groupCollapsed
console.groupEnd
console.info
console.profile
console.profileEnd
console.table
console.time
console.timeEnd
console.timeStamp
console.trace
console.warn

Docs for Google Chrome DevTools also may help you: https://developers.google.com/chrome-developer-tools/docs/commandline-api

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top