Javascript strings and objects - javascript

In js can I call a function in an object from a string? Hm, I show you with an example:
var Object = {
callMe : function() { }
}
Object.callMe();
This I can do, but what if I want to do this:
var string = 'callMe';
Object.string();
Can I somehow do this? Maybe I'm just thinking wrong here

For this use bracket notation, like this:
var string = 'callMe';
Object[string]();
You can test it out here.
In JavaScript obj.thing (dot notation) is accessing the same thing as obj["thing"] (bracket notation).

var myObject = {
myFunction: function() { return "Hooray!"; }
}
var methodName = "myFunction";
alert( myObject[methodName]() );

Related

Execute function off of variable

I am quite newish at nodejs and javascript in general, and I have been trying to figure out how to make a function that executes on a variable, e.g.
var string = "Hello there";
var string1 = "Hello there again"
string = string.function();
string1 = string.function();
I am aware that this can be achieved by doing something like this function(string);, but I am a massive fan of more "inline code" and would like a nicer way to do it.
To achieve this you make your string variable an object
var string = {
text: "Hello there",
func: function(value) {
return value;
}
}
string.func(string.text); // Hello there
Edit: If you want your function to work on all strings add a method in String.prototype like so
String.prototype.your_function = function (char) {
// work on char here
return char
};
You can add custom functions to built in JavaScript object prototypes to your need.
For example in the case of your string approach, you can add a custom property to String.prototype like this:
String.prototype.myFunction = function() {
return 'Value from myFunction: ' + this.valueOf();
}
And when you declare a string you can go and call your new function inline:
var s = 'my string';
s.myFunction();
And it will return:
"Value from myFunction: my string"
Hope it helps!
I think this what you need
String.prototype.function = function ()
{
return this + " world";
};
var x = "hello";
var y = x.function();
console.log(y);

Concatenating chosen random property to object to get the array?

I have an object with a few arrays in it. I am trying to return one of the arrays randomly. I have a function that returns one of the properties in the object, but I am not sure how to use it when concatenating it to the object name. For example:
Object:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
To get a certain array I would do myObj.itemOne which will return the first array. But I want to randomly return an array. I have a function that will return itemOne, itemTwo, or itemThree randomly, but when concatenating what the function returns with myObj. it does not work. What can I do. Here is the function:
function pickRandomProperty(myObj) {
var result;
var count = 0;
for (var prop in myObj){
if (Math.random() < 1/++count){
result = prop;
}
}
return result;
}
var getItemInObject = pickRandomProperty(myObj);
Using what getItemInObject returns, I try to concatenate it with myObj to return the array. How would I do that? Here is what I have tried:
var getItemInObject = pickRandomProperty(myObj);
var randProp = myObj.getItemInObject;
or even:
var randWord = myObj + '.' + getItemInObject;
Which returns '[object Object].itemTwo'
Here is a fiddle: http://jsfiddle.net/xrk7b4zs/
Thanks for any help
You use brackets notation:
var getItemInObject = pickRandomProperty(myObj);
var randProp = myObj[getItemInObject];
// ^ ^
In JavaScript, you can refer to a property using dot notation and a property name literal (obj.foo), or brackets notation and a property name string (obj["foo"]) (or Symbol in ES6+, but that's not relevant here). In that second case, the string can be the result of any expression, including a variable reference.
Live Example:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var result;
var count = 0;
for (var prop in myObj){
if (Math.random() < 1/++count){
result = prop;
}
}
return result;
}
var getItemInObject = pickRandomProperty(myObj);
var array = myObj[getItemInObject];
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(array) + "</pre>"
);
Side note: There's a much easier way to pick a random property, assuming you only care about the object's "own" properties (not ones from its prototype):
function pickRandomProperty(myObj) {
var keys = Object.keys(myObj);
return keys[Math.floor(Math.random() * keys.length)];
}
Live Example:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var keys = Object.keys(myObj);
return keys[Math.floor(Math.random() * keys.length)];
}
var getItemInObject = pickRandomProperty(myObj);
var array = myObj[getItemInObject];
document.body.insertAdjacentHTML(
"beforeend",
"<pre>" + JSON.stringify(array) + "</pre>"
);
You can concatanate strings, not code. To access an object property from a variable, use the bracket notation:
var randWord = myObj[getItemInObject];
http://jsfiddle.net/xrk7b4zs/2/
However, even this code will only return the object property which is an array of strings, and judging by your variable name, you might want to pick a random string from that array.
note: if for some reason you have to go with the dot notation, you can evaluate the concatted string using eval but it's not recommended in +99% of cases.
var getItemInObject = pickRandomProperty(myObj);
console.log(getItemInObject)
var randWord = myObj[getItemInObject];
You need to do myObj[getItemInObject];
Upadated Fiddle
You can use eval that evaluates string as javascript code :
var randWord = eval('myObj.' + getItemInObject);
Working Fiddle
you can Achieve the Object Property by two Way
using "." operator and 2. using passing key String in [""].
You used in your code here :
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
you can get your Object Property value by two ways here
1. myObj.itemOne // this way you used when you know what value you want to return.
2. myObj["itemOne"] // this way you will used when you want to access you object Property in generic Way. i recommend you to use this way.
In your code:
var getItemInObject = pickRandomProperty(myObj);
this variable contained your give your object.property name which is you return by running Function.
var getItemInObject = pickRandomProperty(myObj);
So You can pass this variable Like This for accessing randomly your object property value
var randWord = myObj[getItemInObject];
console.log(randWord);
I hope this Answer will help you to achieve which you want. it will give you result like.:
var myObj = {
itemOne:['blue','red','green'],
itemTwo:['sky','grass','book'],
itemThree:['day','month','year']
}
function pickRandomProperty(myObj) {
var result;
var rKey = Math.floor((Math.random()*3)+1) -1;
return myObj.itemOne[rKey];
}
var getItemInObject = pickRandomProperty(myObj);
var randWord = 'myObj.itemOne' + '.' + getItemInObject;
console.log(randWord);
It works!!!

Convert JSON to JavaScript Object of Type X

I know all about JSON.stringify or JSON.parse in the sense that one serializes an object and one deserializes the string back into an object. This is great!
However, I have the following situation:
var i = new MyMagicalObject();
var oi = JSON.parse(JSON.stringify(i));
console.log(i.numFields()); // this is fine
console.log(oi.numFields()); // this throws since Object has no method 'numFields'
Basically, I'd like to treat oi as an instance of "MyMagicalObject" since that's what it is.
I'm sure there's some magic about setting the prototype on oi or something, but I'm fairly new to JavaScript. Any help would be appreciated.
You can't "store" JavaScript functions in JSON strings.
The only data types that can be stored in JSON are:
Number
String
Boolean
Array
Object
null
(source)
Anything that isn't one of those types, gets ignored:
function Test(){
this.foo = function(){
return 'bar';
}
this.theAnswer = '42';
}
var t = new Test();
alert(t.foo());
alert(JSON.stringify(t))
Your problem could be easily solved by redesigning your MyMagicalObject class. Here is an example of JSON-friendly class:
function MyMagicalObject(props) {
this.props = props || {};
}
MyMagicalObject.prototype.get = function(key) {
return this.props[key];
};
MyMagicalObject.prototype.set = function(key, val) {
this.props[key] = val;
return this;
};
MyMagicalObject.prototype.toJSON = function() {
return this.props;
};
MyMagicalObject.prototype.numFields = function() {
return Object.keys(this.props).length;
};
This realization follows two rules:
It's constructor accepts JSON representation as a first argument.
It provides toJSON method to tell JS engine how to convert its instance to JSON.
Check the following example:
var obj = new MyMagicalObject();
obj.set('foo', 42).set('bar', 'baz');
alert(obj.numFields()); // 2
var str = JSON.stringify(obj);
var obj2 = new MyMagicalObject(JSON.parse(str));
alert(obj2.numFields()); // 2
You can create a new MyMagicalObject() and then overwrite its properties with the one from oi.
var t = new MyMagicalObject();
for(var k in oi) t[k]=oi[k];
That should do the trick. If you have a more complex object (with more than 1 dimension), search for a copy function that deep copies all properties.
Add oi.prototype = MyMagicalObject.prototype; after line 3.
or
create a new object and copy the properties:
var oi2 = new MyMagicalObject();
for (var p in oi) {
if (oi.hasOwnProperty(p)) {
oi2[p] = oi[p]
}
}
console.log(oi2.numFields());

How to call object and its method with a variable

I have a bunch of jQuery objects with a init method, so right now I have something like this
$.myobject1.init(somevar);
$.myobject2.init(somevar);
$.myobject3.init(somevar);
$.myobject4.init(somevar);
$.myobject5.init(somevar); // somevar is the same var in all the calls
but I'm looking for a way to simply this code, something like this
var objectName = "myobject1"; // or any other object name
$. objectName .init(somevar);
thanks for the help! :-)
Since they are already jQuery objects you don't need $. and you can use .add() like this :
var object = myobject1.add(myobject2).add(myobject3).add(myobject4).add(myobject5);
object.init(somvar)
Just use
$[objectName].init(somevar);
in javascript, all objects are maps. it's really weird, but it means you can do this trick:
var p = "mypropertyname";
var obj = {};
obj[p] = somevalue;
then, if you do:
console.log(obj.mypropertyname)
you'll get:
> somevalue
If you mean you want to loop through the names of your objects, then you should know that you can't combine strings with dot notation:
var someObj = {
subObj: {
a: 5
}
};
someObj.subObj.a === 5; // true
someObj."subObj".a === 5; // throws error
But you can use strings with square bracket notation:
someObj["subObj"].a === 5; // true
var propName = "subObj";
someObj[propName].a === 5; // true
So you can use that to loop through your object names with a for loop, or you can use a jQuery method as suggested in other answers.

Javascript: How can I transform an array?

I have this on a javascript var: (it's a http returned data, and I don't know if it's an array or string - (how can we see that?) - Update: using typeof returned "string", so it's a string.
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]
How can we pass/transform that, into something like this:
["gggg.fa","rarar.fa"]
?
Thanks a lot,
MEM
You can figure out if is a string or an already parsed object by checking the type of your variable, e.g.:
ajax('url', function (response) {
alert(typeof response);
});
You will now figure out if it's a "string" or an Array "object".
If it's a string, you can use the JSON.parse method as #alcuadrado suggest, otherwise you can simply use the array.
Several answers suggest the use of the for-in statement to iterate over the array elements, I would discourage you to use it for that.
The for-in statement should be used to enumerate over object properties, to iterate over Arrays or Array-like objects, use a sequential loop as #Ken Redler suggests.
You should really avoid for-in for this purpose because:
The order of enumeration is not guaranteed, properties may not be visited in the numeric order.
Enumerates also inherited properties.
You can also use the Array.prototype.map method to meet your requirements:
var response = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var array = response.map(function (item) { return item.nomeDominio; });
// ["gggg.fa", "rarar.fa"]
This question is strongly related with this one.
I would suggest reading my answer there, as it would really help; and with a little variation, it would just work:
var responseString = '[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]',
responseObject = JSON.parse(responseString),
nombresDeDominio = [];
for(var i in responseObject) {
nombresDeDominio.push(responseObject[i].nomeDominio)
}
Suerte!
Assuming your data always looks like that, you can do something like this:
var foo = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var newarr = [];
for ( var i=0,j=foo.length;i<j;i++ ) {
newarr.push( foo[i]['nomeDominio'] );
}
Here's a working fiddle.
function transform(array, f) {
var ret = [];
$.each(array, function(index) {
var v = f.call(this, index);
if(v) {
ret.push(v);
}
});
return ret;
}
var result = transform(
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}],
function() { return this.nomeDominio; }
);
alert(result.toString());
it's a http returned data, and I don't
know if it's an array or string
It's JSON, and you can use it directly in JavaScript.
If you transform it into your array, you will lose the association key / value ; are you sure it's what you want ?
Okay, firstly to get the type of a "thing", use the "typeof" operator (note that the type of an array is an object, not 'array'!):
var a = "string";
var b = 1;
var c = new Array();
alert(typeof(a)); // string
alert(typeof(b)); // number
alert(typeof(c)); // object
To get at the values in the associative array (assuming it is one), you can just loop through it, like so:
var d = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
d["bob"] = "alice";
d["gary"] = "stephen";
for(var key in d) {
alert(d[key]);
}

Categories