Let's assume i have JS code like this:
var foo = new Array('foo', 'bar');
var bar = new Array();
bar.push(foo);
console.log(bar);
The console log only gives me:
Array [ Array[2] ]
I am looking for way to get true log in console. In this case array with subarrays and so on. Something similar to PHP:
echo '<pre>' . print_r($bar, TRUE);
Use dir instead of log. It gives an interactive view.
Chrome/Opera/Firefox all allow for further inspection of arrays via console.log().
Try Firebug also for additional debugging ability.
If your browser supports it, you can also use the JSON.stringify() function. It's best explained with an example:
var a = [
"123",
{ "foo": "bar" },
[ "inner", "array", [ "inner-inner", "array-array" ] ]
];
console.log( JSON.stringify(a) );
// "["123",{"foo":"bar"},["inner","array",["inner-inner","array-array"]]]"
Basically the function converts objects into a JSON string format allowing you to see each object/array and all of it's sub-elements in a plan, string-like format.
Keep in mind that this method will only be effective if the object you are trying to view only contains simple types of data... Function definitions within objects and more complex built-in objects such as window or document will not yield useful information.
Related
I'm learning to program in Javascript and I'd like some help/clarification.
I declared an array that contains animal names. I defined a function that I use to split a string in two. Then I create an empty object literal and add an animal and corresponding breed. I'm trying to invoke the separateWords function in the object literal, but I need some clarification. Here's my code:
var myPets = ["Bengal Bobcat", "Beagle"];
var separateWords = function (string) {
return string.split(" ");
};
var nameCollection = {};
nameCollection.cat = separateWords(myPets[0]);
nameCollection.dog = myPets[1];
nameCollection.fish = null;
When I enter console.log(nameCollection) I get the following:
Object {cat: Array[2], dog: “Beagle”, fish: null}
cat: Array[2]
0: "Bengal"
1: "Bobcat"
length: 2
However, when I enter console.log( separateWords(myPets[0])), I see:
[“Bengal”, “Bobcat”]
I don’t understand why the value of cat shows up as Array[2].
The console displays it as Array[2] as it would be (potentially) unreadable if it expanded it fully. One way to see everything is to stringify it using JSON.stringify which goes through each item in the object recursively and calls toString() on it:
var myPets = ["Bengal Bobcat", "Beagle"];
var separateWords = function (string) {
return string.split(" ");
};
var nameCollection = {};
nameCollection.cat = separateWords(myPets[0]);
nameCollection.dog = myPets[1];
nameCollection.fish = null;
document.body.textContent = JSON.stringify(nameCollection);
You are assigning to cat the result of the separateWords() function call, passing myPets[0] as a parameter.
separateWords() returns an array and with the myPets[0] input it returns a new array with the "Bengal" and "Bobcat" values splitted by the whitespace.
The split() function is the one creating an array with the splitted values and this result is returned by your separateWords() function, which also is the value assigned to the cat object member.
Each browser implements its console like it wants.
So your browser decided to implement the behavior you describe.
If you don't like it, propose a better idea to the developers of this browser. Or use another browser.
I am going to assume you are using Chrome Developer Tools or Firebug.
Developer tools condenses arrays and objects into easily readable lines you then inspect further with. What I mean is, you push the little arrow next each line in the console log to further inspect each object. I will use pictures to explain this.
Here I am assigning an array and then assigning an element in an object to that array as so:
As you can see when I log the object it show's an Array[2] rather than expand the array. In this next picture I then expand the array to inspect it.
Why is this exactly? My first thought is ease of readability. If you have an app that is complex and you have numerous debugging console logs, you can see all the logs on single lines making it easier to hunt down specific logs. As well, if you have a very large and complex object, it is arguably easier to read all the root elements on each line without expanding all the objects and arrays found within that object recursively.
String.prototype.split() returns an array containing the two values in the string which have been split. Read through this.
nameCollection.cat = separateWords(myPets[0])[0]; // nameCollection.cat == Bengal
nameCollection.cat = separateWords(myPets[0])[1]; // nameCollection.cat == Bobcat
This is simply how javascript (and many other languages) work. When you try to print "nameCollection" javascript doesn't automatically do a nice job of printing the cat array. Instead, it simply prints some type related information, which in this case is saying "cat" is an array of length 2.
Is there exist any kind of c# dictionary in JavaScript. I've got an app in angularjs that requests data from an MVC Web Api and once it gets, it makes some changes to it. So the data is an array of objects, which is stored in the MVC Web Api as a Dictionary of objects, but I convert it to list before passing it throug network.
If I convert the Dictionary directly to JSon I get something like:
array = [ {Id:"1", {Id:"1", Name:"Kevin Shields"}},
{Id:"2", {Id:"2", Name:"Natasha Romanoff"}}
];
Well the objects are a little more complex, but you've got now an idea. The problem is that this format is even harder to operate with (I've got alphabetical keys or ids). So is there any equivalent to a dictionary? It's quite simple to do thing like:
Object o = dictionary["1"];
So that's it, thank in advance.
You have two options really, although both essentially do the same thing, it may be worth reading a bit more here, which talks about associative arrays (dictionaries), if you wish to tailor the solution:
var dictionary = new Array();
dictionary['key'] = 'value'
Alternatively:
var dict = [];
dict.push({
key: 'key',
value: 'value'
});
Update
Since ES2015 you can use Map():
const dict = new Map();
dict.set('{propertyName}', {propertyValue});
I know this question is a bit older, but in ES2015 there is a new data structure called map that is much more similar to a dictionary that you would use in C#. So now you don't have to fake one as an object, or as an array.
The MDN covers it pretty well. ES2015 Map
Yes, it's called an object. Object have keys and values just like C# dictonaries. Keys are always strings.
In your case the object would look like this:
{
"1": {
"Id": 1,
"Name":" Kevin Shields"
},
"2": {
"Id": 2,
"Name": "Natasha Romanoff"
}
}
The default ASP.net serializer produces ugly JSON. A better alternative would be Json.NET.
My Example:
var dict = new Array();
// add a key named id with value 111
dict.id = 111;
//change value of id
dict.id = "blablabla";
//another way
// add a key named name with value "myName"
dict["name"] = "myName";
//and delete
delete dict.id;
delete dict["name"]
//another way
dict = {
id: 111,
"name": "myName"
};
//And also another way create associate array
var myMap = { key: [ value1, value2 ] };
I'm scratching my head here why I can't figure this out. It should be easy. I am trying to work with a Javascript object which looks like so:
Object {object: "clip", function: "list", data: Object, items: 1} (console log )
This Object is stored in a variable called data.
if I do var items = data.items I get the number I expect (1). What I cannot seem to get is what is in the data section.
The data.data logged to the console looks like this:
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"…}
I would expect if I wanted the Clipid I would be able to do:
var Clipid = data.data['Clipid'] or data.data.Clipid; however this always comes up null.
I've tried a number of things, but nothing works. I'm sure it's something silly or small I'm missing but any insight is appreciated. Thanks!
If it helps the data comes from jQuery.parseJSON( jsonString )
Note ** If I do this:
var objd = data['data'];
var arv = $.map(objd, function (value, key) { return value; });
I am able to get values like arv[0] etc but I'd prefer to go by key if possible...
Note 2 - It's the JSON Formatting I'm decoding
Hey sorry about this, I noticed the encoding is borked. It looks like if I do:
console.log( data.data["\u0000Clip\u0000id"] ); it wotks! It must have to do with the json_encode.
There's a small typo I guess-
data.data.Clipid
note the small i
It looks like the data is an object, not a dictionary, so you would do var Clipid = data.data.Clipid; to get at the information inside.
You can't do data.data['Clipid'] because you named the attributes using string literals, and the proper syntax you used (data.data.ClipId) has a typo, as mentioned.
if your "Object" in the "data" variable, you just have to do
var clipid = data.Clipid;
var object = {object: "clip", function: "list", data: {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}, items: 1}
console.log(object);
Object {object: "clip", function: "list", data: Object, items: 1}
console.log(object.data)
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}
console.log(object.data.Clipid)
1
This works fine for me, we would need to see your code to see why you are specifically having problems.
It had to do with the JSON encode method in PHP... All the answers stated was what I had tried and are correct, it was just a valid JSON string which had had unexpected unicode characters.
To fix it I needed to do this: $json = str_replace('\u0000', "", json_encode( $response )); Where response was my array of data to be cnverted
In my node REST application I have a function that queries a database for several records and returns an array of objects.
Since I want it to return a JSON object, I need a way to convert the array of objects to a single object with all the records inside.
Unfortunately I can't find an example on the internet about doing something like this.
Any help would be appreciated.
Why would you want to do that ? Its totally fine to JSON stringify an Array of items, you'll get a structure like
"[{},{},{},...]"
that is probably even an advantage, because you keep the order of items guaranteed.
See the object function of underscore.js.
Lets assume you have an array of objects with the form:
log {
name: "foo",
log: "bar"
}
Your could do:
var logs,//Array of logs
logObj = {}
for(i=0, i<logs.Length i++) {
logObj[logs[i].Name] = logs[i].log;
}
After the loop logObj should be:
logObj {
foo: bar,
nextName: cool comment,
etc.
}
I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];