I'm currently using javascript eval() to check and create a multidimensional object that I have no idea of the depth.
Basically, I want to know if there's any way to create this multi-depth object. The object can be as deep as result['one']['two']['three']['four']['five']['six']['seven']. I know there are cases where using eval() is perfectly fine, but I'm also worried about performance. I thought about referencing each depth to a new variable, but I don't know how to do pointers in Javascript
create = function(fields, create_array){
var field;
for (j = 0; j < len; j++){
field = fields.slice(0, j).join('');
if (field){
// is there any way to do this without eval?
eval('if (typeof result' + field + ' == "undefined" || !result' + field + ') result' + field + ' = ' + (create_array?'[]':'{}') + ';');
}
}
}
How about
var deep = { one: { two: { three: { four: { five: { six: { seven: 'peek-a-boo!' }}}}}}};
I don't see what "eval()" has to do with this at all; there's no reason to "initialize" such an object. Just create them.
If you wanted to write a function with an API like you've got (for reasons I don't understand), you could do this:
function create(fields, create_array) {
var rv = create_array ? [] : {}, o = rv;
for (var i = 0; i < fields.length; ++i) {
o = o[fields[i]] = create_array ? [] : {};
}
return rv;
}
There doesn't seem to be any point to the "create_array" flag, since you're presumably always using strings for keys.
Never mind, found my way in. I used a recursive function to ensure that the object was created properly.
create = function(create_array, res, path){
var field = fields.shift();
if (field){
if (typeof res[field] == "undefined" || !res[field]) res[field] = (create_array?[]:{});
path.push('["' + field + '"]');
create(create_array, res[field], path);
}
}
var result = {}, strpath = [], fields[];
create(true, result, strpath);
eval('result' + strpath.join('') + ' = value;');
being variable "field" a variable outside the function, that contained the levels of the object. doing result["field"]["name"]["first"] = value without the ["field"] or ["name"] field existing or defined as an object, would throw an error and stop execution, that's why I'm pre-creating the object variable, either as an array or object.
I couldn't find another option for the second eval() though. There's no way to provide a way to access multiple properties on an object without knowing the depth.
Related
I have a function to help me create ad hoc objects and save me time typing.
Additional EDIT: to clarify this function will only ever sit inside an anon function.
(function(){ // clarification of the functions location
var objectPump = function (props, defaults){
var str;
if(typeof defaults === "string"){
defaults = defaults.split(",");
}else
if(typeof defaults === "undefined" || !defaults.isArray){
defaults =[];
}
if(props !== undefined){
if(typeof props === "string"){
props = props.split(",");
}
}else{
throw new TypeError("No properties defined for objectPump.");
}
// create function body
str = "var obj={};";
props.each( function(p,i) {
str += "obj." + p + "=";
if (typeof defaults[i] === "string") {
str += p + "===undefined?" + '"' + defaults[i] + '":';
} else
if (typeof defaults[i] === "number") {
str += p + "===undefined?" + defaults[i] + ":";
}
str += p + ";";
});
str += "return obj;";
str = "return new Function('" + props.join("','") + "','" + str + "')";
// Uses new Function to create the new function
return (new Function(str))(); // Is this dangerous???
}
})(); // wrapped in an anon function
Which lets me create objects without having to name all the properties and code in defaults.
Edit: Use of the above function.
var car = objectPump("colour,year,type", // objects property names
"white,2015,All Wheel Drive"); // object defaults
// or as arrays
var car = objectPump(["colour","year","type"], // objects property names
["white",2015,"All Wheel Drive"]); // object defaults
var cars = [
car("red",2011), // missing property defaults to All Wheel Drive
car("blue",2015,"bike"),
];
var aCar = car("blue",2015,"bike");
// same as
var aCar = {
colour:"blue",
year:2015,
type:"bike"
}; // but saves me having to type out the property names for each new object
To me it looks very similar to using eval and a place a third party harker could get some malicious code in. So far it has been very handy and I am tempted to use new Function for other tasks.
Should I use new Function() to generate code or is it considered bad and/or dangerous for public code.
var car = objectPump("colour,script", // objects property names
"white,\" + alert(\"test\") + \""); // object defaults
console.log(new car('blue, but the nice one')); // throws alert
Do you mean like this dangerous?
To be honest, I don't really like objectPump function. There are other viable options you have:
Use TypeScript and its default values for functions (http://www.typescriptlang.org/Handbook#functions-optional-and-default-parameters)
Use typeof for defining default values even though it's more typing:
function foo(a, b)
{
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
(https://stackoverflow.com/a/894877/99256)
EDIT: The function objectPump does not give your attacker any advantage. 1) If your attacker can modify your JS file, then she will use eval straight away and she does not need any objectPump. 2) If you sanitize all input from your users, there is no problem here.
My primary concern here is that you will eventually shoot yourself in the foot, rather than an attacker will.
I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.
The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name. How can I use the variable name to retrieve the dial_code that it relates to?
JSON
var dialCodes = [
{"name":"China","dial_code":"+86","code":"CN"},
{"name":"Afghanistan","dial_code":"+93","code":"AF"}
];
The following code runs on mouse hover of a country
var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() + ')<br>' + dialCodes[0][countryName].dial_code);
This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair
If you have to support old browsers:
Loop over the entries in the array and compare to the given name:
var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
if(dialCodes[i].name === countryName) {
dialCode = dialCodes[i].dial_code;
break;
}
}
label.html(countryName + ' (' + dialCode + ')');
If you browser support Array.prototype.filter:
dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code
If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code (CN or AF) you could avoid looping if you did this:
var dialCodes = {
CN: { "name":"China","dial_code":"+86","code":"CN" },
AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}
};
var code = dialCodes.CN.dial_code;
Or
var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;
Since it's an array you can use filter to extract the data you need.
function getData(type, val) {
return dialCodes.filter(function (el) {
return el[type] === val;
})[0];
}
getData('code', 'CN').dial_code; // +86
I'm running this code.
var output = {"records": []};
for(i = 0; i < data.length; i++)
output.records[i] = { propertyName : data[i][propertyName] }
I expected the output to be on the following form.
{ "cat" : "mjau" }
{ "dog" : "woff" }
Instead, I get to my surprise this.
{ "propertyName" : "mjau" }
{ "propertyName" : "woff" }
How can I get variable propertyName?
I'm trying to create a parser that will create a number of records that are all cat but, when called from an other place, the records should have dog property instead. I wish to avoid creating two different code pieces for that.
I've found this question, which I suspect contains the answer to my issue. However, due to ignorance, I don't get it.
Keys in object literals won't be evaluated in JavaScript. So, you need to create an empty object ({}) and then assign the key dynamically:
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName]
var a = {b:'c'}
is just like
var a = {};
a['b'] = 'c';
What you want is
a[b] = c
that is
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName];
You have in this MDN document : Working with objects.
In { propertyName : data[i][propertyName] } the property name part should be constant string. It you pass a variable it wont fetch its value.
What you have to do is
for(i = 0; i < data.length; i++){
var a = {};
a[propertyName] = data[i][propertyName];
output.records.push(a);
}
You can try this:
'"' + propertyName + '"' : ...
I need a way to add an object into another object. Normally this is quite simple with just
obj[property] = {'name': bob, 'height': tall}
however the object in question is nested so the following would be required:
obj[prop1][prop2] = {'name': bob, 'height': tall}
The clincher though, is that the nesting is variable. That is that I don't know how deeply each new object will be nested before runtime.
Basically I will be generating a string that represents an object path like
"object.secondObj.thirdObj.fourthObj"
and then I need to set data inside the fourth object, but I can't use the bracket [] method because I don't know how many brackets are required beforehand. Is there a way to do this?
I am using jQuery as well, if that's necessary.
Sure, you can either use recursion, or simple iteration. I like recursion better. The following examples are meant to be proof-of-concept, and probably shouldn't be used in production.
var setDeepValue = function(obj, path, value) {
if (path.indexOf('.') === -1) {
obj[path] = value;
return;
}
var dotIndex = path.indexOf('.');
obj = obj[path.substr(0, dotIndex)];
return setDeepValue(obj, path.substr(dotIndex + 1), value);
};
But recursion isn't necessary, because in JavaScript you can just change references.
var objPath = 'secondObj.thirdobj.fourthObj';
var valueToAdd = 'woot';
var topLevelObj = {};
var attributes = objPath.split('.');
var curObj = topLevelObj;
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
if (typeof curObj[attr] === 'undefined') {
curObj[attr] = {};
}
curObj = curObj[attr];
if (i === (attributes.length - 1)) {
// We're at the end - set the value!
curObj['awesomeAttribute'] = valueToAdd;
}
}
Instead of generating a string...
var o="object";
//code
o+=".secondObj";
//code
o+=".thirdObj";
//code
o+=".fourthObj";
...you could do
var o=object;
//code
o=o.secondObj;
//code
o=o.thirdObj;
//code
o=o.fourthObj;
Then you can add data like this:
o.myprop='myvalue';
And object will be updated with the changes.
See it here: http://jsfiddle.net/rFuyG/
I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});