This question already has answers here:
Convert JS object to JSON string
(23 answers)
Closed 7 years ago.
I'm using ES6 I transpile using Babel into ordinary JavaScript.
I want to serialise objects into JSON format and am wondering if ES5,ES6 offers a convenient function to do so.
For Maps and Sets there is a toJSON()-function proposed in ES7
You can use JSON.stringify and pass any kind of variable to it (given that it can be represented in JSON).
It works in all current browsers; in case you need a fallback for a really old browser, you can use Crockford's JSON-js.
However, keep in mind that, regarding objects, only public properties are serialized. There's no a generic way to serialize function variables etc. on the fly.
This is why some special object types provide a toJSON or similar method. In order to use such a function for arbitrary objects, you must pass a function as second parameter to JSON.stringify which checks for the existence of a toJSON function.
For example, the following should work (not tested, just from the top of my mind):
var jsonString = JSON.stringify(someLargeObject, function(key, value){
return (value && typeof value.toJSON === 'function')
? value.toJSON()
: JSON.stringify(value);
});
If your someLargeObject contains a sub-object with a toJSON method, this code would use the object's implementation, otherwise use JSON.stringify.
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.
This question already has answers here:
How is a Javascript string not an object?
(2 answers)
Object and String prototypes are not prototypes of defined strings?
(3 answers)
Closed 4 years ago.
When you create an object in JavaScript, you inherit properties from the Object prototype you can utilize.
But a string is a primitive type, thus there is no prototype. So how am I able to use methods such as substr() and repeat() on a string when there is no prototype the string can inherit those methods from?
For example, when I create a new array and assign it to a variable, I type the variable name into the console and the Array prototype is listed where I have access to methods I can use. But if I create a string and assign the string to a variable, then I type the variable into the console, there is no prototype attached to it.
Does that make sense?
When you access a property on a primitive string, number, or other primitive, the JavaScript engine acts as though you've converted it to the equivalent object and then looks for the property. So for instance:
var str = "hi";
var upper = str.toUpperCase();
The JavaScript engine acts as though that code were written like this (for the purposes of accessing the toUpperCase property):
var str = "hi";
var upper = new String(str).toUpperCase();
Before ES5, the spec said that the JavaScript engine actually did create a string object there and then call the property. As of ES5 that changed slightly (because in strict mode it became possible for this to have a non-object value), but in essence the concept is still the same.
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Javascript: Get deep value from object by passing path to it as string [duplicate]
(5 answers)
Closed 5 years ago.
Consider I've an object myObj
And I've a string representing the path to some property inside it: foo.bar
What is the best way to get it from my object?
If I knew the string ahead I would do myObj.foo && myObj.foo.bar to get it safely
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
But i'm sure there is a better way
It's a duplicate of other question. they provided a great solution:
given a path and an obj get the property value this way
path.split('.').reduce((o, i) => o[i], obj)
A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.
Yep, that sounds like the best way. You can create a helper method that does exactly this, but there's nothing built in to the language or standard libraries to make things simpler than this.
function getFromPath(obj, path) {
var current = obj;
for(let piece of path.split('.')) {
current = current[piece];
}
return current;
}
Usage:
getFromPath({foo: {bar: "hello"}}, "foo.bar"); // "hello"
This question already has answers here:
JavaScript: How to pass object by value?
(14 answers)
Closed 7 years ago.
Is there a way to pass an object by value in Javascript/NodeJS to a function? Or is the limitation built into the language?
You cannot control how JS passes variables (afaik), so it will always pass by reference (some conditions may apply). The proper way to do this is to create a copy of the object and pass that in.
This functionality is built in to jQuery (not terribly hard to replicate).
var clone = function(object) { return $.extend(true, {}, object) };
This will create a deep copy of the object which is safe to pass into methods that may have unintended side-effects.
This question already has answers here:
JavaScript way to tell if an object is an Array [duplicate]
(6 answers)
Closed 7 years ago.
What is the best way to determining the object type is Array and why?.
var arr = [];
// Method #1
Array.isArray(arr);
// Method #2
toString.call(arr) == "[object Array]"
// Method #3
arr.constructor == Array
All three methods can be used to test if variable is of Array type. However, there are some nuances. I will start from the last to first.
Method #3. Will not work if variable in question came from other winndow/frame. In this case, constructor will point the the different Array object and this check will return false. For the same reason, arr instanceof Array is not bullet-proof. So it's not 100% reliable.
Method #2. This is the method that has been traditionally used to verify array type. In fact, Array.isArray polyfill is based on this method. The only disadvantage is that it's cumbersome and verbose.
Method #1. Is the one from ES5 that should finally be used to test array type, no matter what realm array comes from (like iframe). This is is the best in the list.
The prefered method is to use Array.isArray. This is present in the ES5 language specification and quite well supported by the browsers.
If you plan to support old browsers, You can find a polyfill on MDN. The polyfill is basically your second option.
The last option will not work if you play with iframes.
var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false
The reason is that the Array constructor is diffferent for each window object. Using this to detect arrays will work 99% of the time but will suddenly fail one day.