I am currently working a plugin with a settings variable that is fairly deep (3-4 levels in some places). Following the generally accepted jQuery Plugin pattern I have implemented a simple way for users to modify settings on the fly using the following notation:
$('#element').plugin('option', 'option_name', 'new_value');
Here is the code similar to what I am using now for the options method.
option: function (option, value) {
if (typeof (option) === 'string') {
if (value === undefined) return settings[option];
if(typeof(value) === 'object')
$.extend(true, settings[option], value);
else
settings[option] = value;
}
return this;
}
Now consider that I have a settings variable like so:
var settings = {
opt: false,
another: {
deep: true
}
};
If I want to change the deep settings I have to use the following notation:
$('#element').plugin('option', 'another', { deep: false });
However, since in practice my settings can be 3-4 levels deep I feel the following notation would be more useful:
$('#element').plugin('option', 'another.deep', false);
However I'm not sure how feasible this is, nor how to go about doing it. As a first attempt I tried to "traverse" to the option in question and set it, but if I set my traversing variable it doesn't set what it references in the original settings variable.
option: function (option, value) {
if (typeof (option) === 'string') {
if (value === undefined) return settings[option];
var levels = option.split('.'),
opt = settings[levels[0]];
for(var i = 1; i < levels.length; ++i)
opt = opt[levels[i]];
if(typeof(value) === 'object')
$.extend(true, opt, value);
else
opt = value;
}
return this;
}
To say that another way: By setting opt after traversing, the setting it actually refers to in the settings variable is unchanged after this code runs.
I apologize for the long question, any help is appreciated. Thanks!
EDIT
As a second attempt I can do it using eval() like so:
option: function (option, value) {
if (typeof (option) === 'string') {
var levels = option.split('.'),
last = levels[levels.length - 1];
levels.length -= 1;
if (value === undefined) return eval('settings.' + levels.join('.'))[last];
if(typeof(value) === 'object')
$.extend(true, eval('settings.' + levels.join('.'))[last], value);
else
eval('settings.' + levels.join('.'))[last] = value;
}
return this;
}
But I really would like to see if anyone can show me a way to not use eval. Since it is a user input string I would rather not run eval() on it because it could be anything. Or let me know if I am being paranoid, and it shouldn't cause a problem at all.
The issue you're running into here comes down to the difference between variables pointing to Objects and variables for other types like Strings. 2 variables can point to the same Object, but not to the same String:
var a = { foo: 'bar' };
var b = 'bar';
var a2 = a;
var b2 = b;
a2.foo = 'hello world';
b2 = 'hello world';
console.log(a.foo); // 'hello world'
console.log(b); // 'bar'
Your traversal code works great until the last iteration of the loop, at which point opt is a variable containing the same value as deep inside the object settings.opt.another. Instead, cut your loop short and use the last element of levels as a key, like
var settings = {
another: {
deep: true
}
};
var levels = 'another.deep'.split('.')
, opt = settings;
// leave the last element
var i = levels.length-1;
while(i--){
opt = opt[levels.shift()];
}
// save the last element in the array and use it as a key
var k = levels.shift();
opt[k] = 'foobar'; // settings.another.deep is also 'foobar'
At this stage opt is a pointer to the same Object as settings.another and k is a String with the value 'deep'
How about using eval rather than traversal?
var settings = {
opt: false,
another: {
deep: true,
}
};
var x = "settings.another";
eval(x).deep = false;
alert(settings.another.deep);
Would the built in jQuery $().extend() not be exactly what you need?
http://api.jquery.com/jQuery.extend/
*note the second method signature with the first agument of true performs a deep merge...
Related
Suppose I have a json object in which I record the number of visitors to my site, grouped by browser / version.
let data = {
browsers: {
chrome: {
43 : 13,
44 : 11
},
firefox: {
27: 9
}
}
}
To increment a particular browser, I need to check if several keys exist, and if not, create them.
let uap = UAParser(request.headers['user-agent']);
if (typeof uap.browser !== 'undefined') {
if (typeof data.browsers === 'undefined')
data.browsers = {}
if (typeof data.browsers[uap.browser.name] === 'undefined')
data.browsers[uap.browser.name] = {}
if (typeof data.browsers[uap.browser.name][uap.browser.version] === 'undefined')
data.browsers[uap.browser.name][uap.browser.version] = 0
data.browsers[uap.browser.name][uap.browser.version] += 1;
}
The deeper my data structure the crazier things get.
It feels like there must be a neater way to do this in javascript. There's always a neater way. Can anyone enlighten me here?
This shorter code should do the trick:
if (uap.browser) { // typeof is pretty much redundant for object properties.
const name = uap.browsers.name; // Variables for readability.
const version = uap.browser.version;
// Default value if the property does not exist.
const browsers = data.browsers = data.browsers || {};
const browser = browsers[name] = browsers[name] || {};
browser[version] = browser[version] || 0;
// Finally, increment the value.
browser[version]++;
}
Note that you were using === where you should've been using = (in === {}).
Let's explain this line:
const browsers = data.browsers = data.browsers || {};
The last part: data.browsers = data.browsers || {} sets data.browsers to be itself if it exists. If it doesn't yet, it's set to be a new empty object.
Then, that whole value gets assigned to browsers, for ease of access.
Now, shorter code shouldn't be top priority, but in cases like this, you can make the code a lot more readable.
You can give up the if statements and do it like this:
uap.browser = uap.browser || {}
essentially it does the same as the if only much shorter
Here's a very clean and generic solution using Proxy() I have a second solution which is standard ECMAscript 5 if you don't need it so cleanly or need it less browser dependant.
var handler = {
get: function (target, property) {
if (property !== "toJSON" && target[property] === undefined) {
target[property] = new Proxy ({}, handler);
}
return target[property];
}
}
var jsonProxy = new Proxy ({}, handler);
jsonProxy.non.existing.property = 5;
jsonProxy.another.property.that.doesnt.exist = 2;
jsonProxy["you"]["can"]["also"]["use"]["strings"] = 20;
console.log (JSON.stringify (jsonProxy));
You can do the same thing with classes but with a more verbose syntax:
var DynamicJSON = function () {};
DynamicJSON.prototype.get = function (property) {
if (this[property] === undefined) {
this[property] = new DynamicJSON ();
}
return this[property];
};
DynamicJSON.prototype.set = function (property, value) {
this[property] = value;
};
var jsonClass = new DynamicJSON ();
jsonClass.get("non").get("existing").set("property", 5);
jsonClass.get("you").get("have").get("to").get("use").set("strings", 20);
console.log (JSON.stringify (jsonClass));
I'm pretty sure this is impossible but maybe someone clever out there knows if there is a chance of making this work. Is it possible to have code where:
1 myPerson = new Person();
2 myPerson.name = 'Charles Xavier';
Where the code on line #2 automatically checks if myPerson.setName exists and if so calls
myPerson.setName('Charles Xavier');
in place of of doing the direct assignment.
Nope, sorry! It is possible in ES6, though:
var o = {};
Object.defineProperty(o, "name", {
set: function (value) {
console.log("Property 'name' set to: " + value);
// store 'value' somewhere
}
});
c.f. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
related: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
Since this is not possible in < ES6, frameworks like AngularJS use dirty-checking (aka they check the value X times per second) to watch for property changes.
Not for all browser, but there's javascript proxy which is only work on firefox, and make this become useless. :D
var Validator = {
set: function(obj, prop, value){
if(prop == 'name' && setName in obj)
obj.setName(value);
obj[prop] = value;
}
}
var myPerson = new Proxy(Person, Validator);
myPerson.name = 'Charles Xavier'; // This will call Validator.set
json2.js seems to ignore members of the parent object when using JSON.stringify(). Example:
require('./json2.js');
function WorldObject(type) {
this.position = 4;
}
function Actor(val) {
this.someVal = 50;
}
Actor.prototype = new WorldObject();
var a = new Actor(2);
console.log(a.position);
console.log(JSON.stringify(a));
The output is:
4
{"someVal":50}
I would expect this output:
4
{"position":0, "someVal":50}
Well that's just the way it is, JSON.stringify does not preserve any of the not-owned properties of the object. You can have a look at an interesting discussion about other drawbacks and possible workarounds here.
Also note that the author has not only documented the problems, but also written a library called HydrateJS that might help you.
The problem is a little bit deeper than it seems at the first sight. Even if a would really stringify to {"position":0, "someVal":50}, then parsing it later would create an object that has the desired properties, but is neither an instance of Actor, nor has it a prototype link to the WorldObject (after all, the parse method doesn't have this info, so it can't possibly restore it that way).
To preserve the prototype chain, clever tricks are necessary (like those used in HydrateJS). If this is not what you are aiming for, maybe you just need to "flatten" the object before stringifying it. To do that, you could e.g. iterate all the properties of the object, regardless of whether they are own or not and re-assign them (this will ensure they get defined on the object itself instead of just inherited from the prototype).
function flatten(obj) {
var result = Object.create(obj);
for(var key in result) {
result[key] = result[key];
}
return result;
}
The way the function is written it doesn't mutate the original object. So using
console.log(JSON.stringify(flatten(a)));
you'll get the output you want and a will stay the same.
Another option would be to define a toJSON method in the object prototype you want to serialize:
function Test(){}
Test.prototype = {
someProperty: "some value",
toJSON: function() {
var tmp = {};
for(var key in this) {
if(typeof this[key] !== 'function')
tmp[key] = this[key];
}
return tmp;
}
};
var t = new Test;
JSON.stringify(t); // returns "{"someProperty" : "some value"}"
This works since JSON.stringify searches for a toJSON method in the object it receives, before trying the native serialization.
Check this fiddle: http://jsfiddle.net/AEGYG/
You can flat-stringify the object using this function:
function flatStringify(x) {
for(var i in x) {
if(!x.hasOwnProperty(i)) {
// weird as it might seem, this actually does the trick! - adds parent property to self
x[i] = x[i];
}
}
return JSON.stringify(x);
}
Here is a recursive version of the snippet #TomasVana included in his answer, in case there is inheritance in multiple levels of your object tree:
var flatten = function(obj) {
if (obj === null) {
return null;
}
if (Array.isArray(obj)) {
var newObj = [];
for (var i = 0; i < obj.length; i++) {
if (typeof obj[i] === 'object') {
newObj.push(flatten(obj[i]));
}
else {
newObj.push(obj[i]);
}
}
return newObj;
}
var result = Object.create(obj);
for(var key in result) {
if (typeof result[key] === 'object') {
result[key] = flatten(result[key]);
}
else {
result[key] = result[key];
}
}
return result;
}
And it keeps arrays as arrays. Call it the same way:
console.log(JSON.stringify(flatten(visualDataViews)));
While the flatten approach in general works, the snippets in other answers posted so far don't work for properties that are not modifiable, for example if the prototype has been frozen. To handle this case, you would need to create a new object and assign the properties to this new object. Since you're just stringifying the resulting object, object identity and other JavaScript internals probably don't matter, so it's perfectly fine to return a new object. This approach is also arguably more readable than reassigning an object's properties to itself, since it doesn't look like a no-op:
function flatten(obj) {
var ret = {};
for (var i in obj) {
ret[i] = obj[i];
}
return ret;
}
JSON.stringify takes three options
JSON.stringify(value[, replacer[, space]])
So, make use of the replacer, which is a function, that is called recursively for every key-value-pair.
Next Problem, to get really everything, you need to follow the prototpes and you must use getOwnPropertyNames to get all property names (more than you can catch with keysor for…in):
var getAllPropertyNames = () => {
const seen = new WeakSet();
return (obj) => {
let props = [];
do {
if (seen.has(obj)) return [];
seen.add(obj);
Object.getOwnPropertyNames(obj).forEach((prop) => {
if (props.indexOf(prop) === -1) props.push(prop);
});
} while ((obj = Object.getPrototypeOf(obj)));
return props;
};
};
var flatten = () => {
const seen = new WeakSet();
const getPropertyNames = getAllPropertyNames();
return (key, value) => {
if (value !== null && typeof value === "object") {
if (seen.has(value)) return;
seen.add(value);
let result = {};
getPropertyNames(value).forEach((k) => (result[k] = value[k]));
return result;
}
return value;
};
};
Then flatten the object to JSON:
JSON.stringify(myValue, flatten());
Notes:
I had a case where value was null, but typeof value was "object"
Circular references must bee detected, so it needs seen
I'm not terribly good with Javascript so I'm wondering if there is a better way of doing this:
if (games[level] === undefined) {
games[level] = {};
games[level]['pending'] = {};
}
if (!games[level]['pending'].length) {
return game.create(level);
}
In PHP I can just test empty($games[$level]['pending']). Is there a better way of testing for this? Basically all I want to do is create the object if it does not exist.
if (games[level] === undefined) {
games[level] = game.create(level);
}
If there is no such level game create should be called to initialize all of the data needed. I don`t see any point of making it an object and then checking for "pending". It will be always empty, because you just created the object.
If your the second if returns something for games[level]['pending'].length you have a big problem with your code. You can`t create an empty object ( games[level]['pending'] = {} ) and find that it already has properties.
In addition:
games[level] = {};
// games[level]['pending'] = {}; - bad
games[level].pending = {}; // this way object properties should be used
you can make yourself a function to do that, pass it the games object a a string like "level.pending.id.something.something" and goes on and creates the objects.
function makeObj(obj, path) {
var parts = path.split("."), tmp = obj, name;
while (parts.length) {
name = parts.shift();
if (typeof tmp[name] === 'undefined') {
tmp[name] = {};
}
tmp = tmp[name];
}
}
var x = {};
makeObj(x, "this.is.a.test");
games[level] = games[level] || {pending: {}};
if (!games[level].pending.length) {
return game.create(level);
}
I'm looking for a solution to serialize (and unserialize) Javascript objects to a string across browsers, including members of the object that happen to be functions. A typical object will look like this:
{
color: 'red',
doSomething: function (arg) {
alert('Do someting called with ' + arg);
}
}
doSomething() will only contain local variables (no need to also serialize the calling context!).
JSON.stringify() will ignore the 'doSomething' member because it's a function. I known the toSource() method will do what I want but it's FF specific.
You can use JSON.stringify with a replacer like:
JSON.stringify({
color: 'red',
doSomething: function (arg) {
alert('Do someting called with ' + arg);
}
}, function(key, val) {
return (typeof val === 'function') ? '' + val : val;
});
A quick and dirty way would be like this:
Object.prototype.toJSON = function() {
var sobj = {}, i;
for (i in this)
if (this.hasOwnProperty(i))
sobj[i] = typeof this[i] == 'function' ?
this[i].toString() : this[i];
return sobj;
};
Obviously this will affect the serialization of every object in your code, and could trip up niave code using unfiltered for in loops. The "proper" way would be to write a recursive function that would add the toJSON function on all the descendent members of any given object, dealing with circular references and such. However, assuming single threaded Javascript (no Web Workers), this method should work and not produce any unintended side effects.
A similar function must be added to Array's prototype to override Object's by returning an array and not an object. Another option would be attaching a single one and let it selectively return an array or an object depending on the objects' own nature but it would probably be slower.
function JSONstringifyWithFuncs(obj) {
Object.prototype.toJSON = function() {
var sobj = {}, i;
for (i in this)
if (this.hasOwnProperty(i))
sobj[i] = typeof this[i] == 'function' ?
this[i].toString() : this[i];
return sobj;
};
Array.prototype.toJSON = function() {
var sarr = [], i;
for (i = 0 ; i < this.length; i++)
sarr.push(typeof this[i] == 'function' ? this[i].toString() : this[i]);
return sarr;
};
var str = JSON.stringify(obj);
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
return str;
}
http://jsbin.com/yerumateno/2/edit
Something like this...
(function(o) {
var s = "";
for (var x in o) {
s += x + ": " + o[x] + "\n";
}
return s;
})(obj)
Note: this is an expression. It returns a string representation of the object that is passed in as an argument (in my example, I'm passing the in an variable named obj).
You can also override the toString method of the Object's prototype:
Object.prototype.toString = function() {
// define what string you want to return when toString is called on objects
}
It's impossible without the help of the object itself. For example, how would you serialize the result of this expression?
(function () {
var x;
return {
get: function () { return x; },
set: function (y) { return x = y; }
};
})();
If you just take the text of the function, then when you deserialize, x will refer to the global variable, not one in a closure. Also, if your function closes over browser state (like a reference to a div), you'd have to think about what you want that to mean.
You can, of course, write your own methods specific to individual objects that encode what semantics you want references to other objects to have.
JSONfn plugin is exactly what you're looking for.
http://www.eslinstructor.net/jsonfn/
--Vadim
var myObj = {
color: 'red',
doSomething: function (arg) {
alert('Do someting called with ' + arg);
}
}
var placeholder = '____PLACEHOLDER____';
var fns = [];
var json = JSON.stringify(myObj, function(key, value) {
if (typeof value === 'function') {
fns.push(value);
return placeholder;
}
return value;
}, 2);
json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
return fns.shift();
});
console.log(json)
https://gist.github.com/cowboy/3749767