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!!!
Related
Trying to return all key values of givenName but it gets nothing.
I"m new to this is...
window.location.href = 'gonative://contacts/getAll?callback=contacts_callback';
function contacts_callback(data) {
var obj = JSON.stringify(data);
var obj = JSON.parse(obj);
var givenName = obj.contacts[0].givenName;
var keys = Object.keys(obj.contacts.givenName);
document.getElementById("demo").innerHTML = keys;
}
assuming obj.contacts is an array of objects, each having a givenName property
Since obj.contacts is an array, it is unlikely to have a givenName property itself (it could, but then you wouldn't be getting that through JSON)
var keys = Object.keys(obj.contacts.givenName);
is same as
var keys = Object.keys(undefined);
and you should be getting an error in the browser developer tools console at this point
You'll want to use Array#map function as follows
function contacts_callback(obj) {
var givenNames = obj.contacts.map(({givenName}) => givenName);
document.getElementById("demo").innerHTML = givenNames;
}
Note
function contacts_callback(data) {
var obj = JSON.stringify(data);
var obj = JSON.parse(obj);
besides the obvious error (doesn't bother javascript though) of declaring the same variable twice (obj), the code is identical to:
function contacts_callback(obj) {
Note: however, that if the code inside the function were to mutate any values in obj, then, the original code should be used if you do not want to make changes to the passed in object
I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?
function getFromSomewhere(arg1) {
string newName = arg1 + "sampleWord";
var (use NewName here) = [];
}
Not allowed, unfortunately. Variable names, such as newName, that we see are rid of at compilation time for optimization. Your machine will have no use for it's name newName during runtime, which is when you're trying to assign the name to it.
You could use an object with the wanted fruits as key for the array, like in the example.
The object is easy to access and to maintain.
var array = ["apple", "banana", "grapes"],
prices = {};
array.forEach(function (k) {
prices[k] = [];
});
prices.apple.push(1, 10, 3);
console.log(prices.apple[2]);
console.log(prices);
You can use newName as the name of a property
function getFromSomewhere(arg1) {
var myVariableNamedAtRuntime = [];
string newName = arg1 + "sampleWord";
myVariableNamedAtRuntime[newName] = [];
}
and then access the array as ...
myVariableNamedAtRuntime[newName]
There is no way you can add new variables to the function definition after the function is defined.. However you can always add new properties to the function object defined or it's prototype and you can access them as follows;
function getFromSomewhere(arg1) {
var newName = arg1 + "_sampleWord_";
this.getFromSomewhere.varName = newName + "test";
this.getFromSomewhere.prototype.varName = newName + "best";
console.log(this.getFromSomewhere.varName);
console.log(this.getFromSomewhere.prototype.varName);
}
getFromSomewhere("test");
You can add the variable to the window object:
function getFromSomewhere(arg1) {
var newName = arg1 + "sampleWord";
window[newName] = [];
}
getFromSomewhere("blip");
console.log(blipsampleWord); // You'd get []
Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:
function namesToObj(arr){
return arr.map( name => ({
name,
price:10
}));
}
namesToObj(["banana","tomato"])
/*results in
[{name:"banana",price:10},{name:"tomato",price:10}]
*/
Let's say I have a complex object with properties that have properties.
var x = {};
x.A.B = 'Hello';
x.A.C = 'World!';
x.D.E = 100;
x.D.F = 2.5;
Is there anything I could put in a single set of square brackets in order to get back any of these properties? A simple test shows that x['A.B'] does not return 'Hello'. Is there any syntax for doing this?
If you don't want to iterate you could do it fairly safe with eval in strict mode. Not that I recommend doing this. But it's a way to do it.
var x = {A:{}};
x.A.B = 'Hello';
var propertyPath = 'A.B';
var value = eval('"use strict"; x.' + propertyPath);
console.log(value);
Another more reusable way would be to create a new Function object instead of using eval.
function propertyValue(obj, propertyPath) {
'use strict';
return (new Function('obj', 'return obj.' + propertyPath))(obj);
}
var value = propertyValue(x, 'A.B');
It is practically the same but has a clear definition.
var b = '1';
How can I create a variable name using the contents of variable b? I am doing this in a each loop, so b will change.
I am wanting the final product to be something like:
var trip1 = '';
How would I accomplish something like that?
var trip + b = '';
var trip.b = '';
No, but you can do it with properties of an object:
var obj = {};
obj.b = '1'
obj['trip' + obj.b] = '';
// or
var obj = {};
var b = '1'
obj['trip' + b] = '';
In JavaScript, you can access properties in two ways:
Using a dot and a literal property name, e.g. obj.trip1.
Using brackets and a string property name, e.g. obj['trip1'].
In the latter case, the string doesn't have to be a string literal, it can be the result of any expression, hence the examples above.
I am doing this in a each loop
Since you are iterating over them, the best way to do this is to use an array.
var trip = [1,2,3,4,5];
for (var i = 0; i < trip.length; i++){
alert(trip[i]);
}
To address your question, you could store your values as properties of an object:
var obj = {};
var b = '1';
obj['trip' + b] = "";
If you are doing this in the global scope, you could also add the variable as a property of the global object:
var b = '1';
window['trip' + b] = "";
trip1; // == ""
you can access global variables via the window object, using a dynmamic key like this:
var b = '1';
trip1 = 'hello';
console.log(window['trip'+b]);
It sounds like you are looking for the eval() method.
var b = '1';
(eval('var trip'+b+' = 3')); // Is the same as writing var trip1 = 3;
console.log(trip1);
//Output of variable trip1 is 3
Although, do a quick google search for why eval(); is bad before you employ this technique.
Consider:
function Shape() {
this.name = "Generic";
this.draw = function() {
return "Drawing " + this.name + " Shape";
};
}
function welcomeMessage()
{
var shape1 = new Shape();
//alert(shape1.draw());
alert(shape1.hasOwnProperty(name)); // This is returning false
}
.welcomeMessage called on the body.onload event.
I expected shape1.hasOwnProperty(name) to return true, but it's returning false.
What is the correct behavior?
hasOwnProperty is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).
You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").
hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")
Try this:
function welcomeMessage()
{
var shape1 = new Shape();
//alert(shape1.draw());
alert(shape1.hasOwnProperty("name"));
}
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
for(i in obj) {
alert("The value of obj." + i + " = " + obj[i]);
}
hasOwnProperty() is a nice property to validate object keys.
Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true