Came across this snippet
var someDataJSON = jQuery.parseJSON(JSON.stringify(someData));
According to MDN the inner "method converts a JavaScript value to a JSON string"; then the outer method "Takes a well-formed JSON string and returns the resulting JavaScript value" per jQuery
If you start with a JS value & end up with a JS value, is this a pointless operation?
Usually that is a trick used to get a by-value copy of an object in javascript. (Since all objects are passed by reference). You can find a more in-depth answer on how to accomplish this, if you're curious, in this stackoverflow post
If someDataJSON is a flat JSON object, this way you get a copy of that object. Since, there is no direct method to copy a javascript object "by value" [and not "by reference"], this trick can be used.
var copyJSONObj = JSON.parse(JSON.stringify(JSONObj))
So, there is some point after all.
Related
I was looking for the answer to this and I could't find a very good answer but is arrays considered a collection in javascript.
I know that map is considered a collection but wasn't sure about Javascript
it's pretty basic really. It's reading the value in editTextNumber1 and storing it in a variable named edittextNumber1intvalue.
Fun fact about reading text values from controls in android: You can't just "getText(). If you do, you get an object that i believe is a stringbuilder. You have to use the .toString() method of the returned object.
Now on to part 2: Since the value returned is a string, you can't just force that into an integer. It has to be converted. Integer.parseInt will return an integer value if the string passed into it is numeric.
And that's it.
I have multiple Hashmap in my javavscript code and I'm trying to dynamically load the relevant map according to the name passed to the function.
The problem is when I pass the value as string value it actually tries to get the keys of the string rather than the object which it refers to.
This jsfiddle properly illustrates my problem.
Line 13 gives the expected output whereas Line 14 creates keys out of the string name.
Its basically the difference between:
Object.keys(PROP_ONE)
and
Object.keys("PROP_ONE")
While the first is an identifier resolved to an object, the second one is just a string. not more. You may access it using bracket notation due to the fact that its part of window:
Object.keys(window["PROP_ONE"])
Disclaimer:
All in all, dynamic keys should just be used if really neccessary. They make your code slower and more buggy.
When I use the System.Web.Script.Serialization.JavaScriptSerializer.Serialize method, I get back valid JSON code.
This is usually perfect, but sometimes I want to get back the result as a Javascript object, not JSON. The Serialize method has an overload that takes a SerializationFormat parameter. That looks perfect... but it is marked as internal!
How can I get out a string of Javascript from the Serializer?
Take a look at the JScript DLL Eval object's JScriptEvaluate method (http://msdn.microsoft.com/en-us/library/microsoft.jscript.eval.jscriptevaluate.aspx):
using Microsoft.JScript;
var MyJSObject = Eval.JScriptEvaluate("{a:'Property1',b:'Property2'}", Engine);
I'm attempting to convert a JSON object to a "normal" object using the following...
var slaobj = eval('('+s+')');
s being the JSON. however, it doesnt seem to work (It's `.length' is coming back as undefined). What am I doing wrong?
It's `.length' is coming back as undefined
It won't necessarily have a length property, unless it's an array or some other object that has one. For example:
var json = '{"foo": "Value of foo"}';
var obj = eval('(' + json + ')');
alert(obj.foo); // alerts "value of foo"
alert(obj.length); // alerts "undefined", there's no `length` in `obj`
Live example
Off-topic: Using eval to deserialize JSON text can be a security problem, unless you can unambiguously trust the source of the JSON text (for instance, it's your own server and you're connecting via SSL), because eval doesn't parse JSON, it parses and runs JavaScript code. (Adding the parentheses doesn't really help.) You can get alternatives to using eval from Douglas Crockford's Github page (he's the inventor of JSON). Last I checked, there are three alternatives there, two of which don't use eval at all; see the README at the bottom of the page for details.
Objects don't all have ".length" properties. An object literal like:
{ 'foo': 100, 'bar': 'Abraham Lincoln' }
describes an object that has no ".length" property.
JavaScript Array objects have ".length" properties because of the way the language runtime works. But a plain object in JavaScript only has such a property if you put it there.
How are you retrieving the object?
I would say there has to be something else wrong - are you sure the 's' JSON object was returned correctly?
JSON.org
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
Update: Ah, I see, that's what the parentheses are for. Rats. Deleted the first part.
But this remains valid:
Don't use eval!
eval() is a dangerous function, which
executes the code it's passed with the
privileges of the caller. If you run
eval() with a string that could be
affected by a malicious party, you may
end up running malicious code on the
user's machine with the permissions of
your webpage / extension. More
importantly, third party code can see
the scope in which eval() was invoked,
which can lead to possible attacks in
ways of which the similar Function is
not susceptible.
Source: Mozilla JavaScript Reference: eval()
http://www.jsonlint.com/ this site has good JSON string validation which you should have at your disposal all the times. It's good to validate the JSON string when its really big.
Also do not user the eval() to get the JSON object. Visit http://www.json.org/ it has really nice guide lines check it.
There are many JavaScript libraries today which offers JSON API. I will suggest you to user one of it for safety.
http://api.jquery.com/jQuery.getJSON/
http://developer.yahoo.com/yui/json/
http://dojotoolkit.org/reference-guide/dojo/_base/json.html
var username = $("#username"),
password = $("#password"),
allFields = $([]).add(username).add(password);
What is allFields? What is $([])?
Being a newbie to Javascript/jQuery, I've never seen this $([]) notation before and I'm interested in its associated methods.
Given that its "$([])", it's tricky to search for. And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing.
So what is $([])? Can anyone point me to some documentation? I'm interested in learning how to use this strange thing.
The jQuery function accepts an array of DOM nodes.
$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array.
Calling the jQuery function without any arguments returns an empty set. Taken from jQuery docs,
Returning an Empty Set
As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.
So, your example would work the same if you had instead called
$().add(username).add(password);
As other answers have mentioned and the docs say, passing an empty array was required before v 1.4.
[] it's an empty array. Wrapping it with $() overcharges it with jQuery's functions.
In javascript you can create an array this way:
var foo = [];
It is an empty array being passed in the creation of a jQuery object. Presumably to initialize something.
Shouldn't be necessary, at least not in the latest versions of jQuery.
Here's an example without the Array: http://jsfiddle.net/MAzLN/
Works fine, as the alert() shows one element in the object.
jQuery initializes the length property to 0 when the object is created, so I'm not sure what the purpose is, unless it was required in the past.
I believe it creates an empty jQuery collection object.