Calling json object dot notation with a variable - javascript

Hi i have a json object to access the path is
data.Application.Exabeam
const target = data.Application.Exabeam
I have trouble , I would like to replace the "Exabeam" to be referenced by a variable
I tried to add a variable as follows
var casetypesession = sessionStorage.getItem("homepageclicksession");
a) const target = data.Application.casetypesession; (dosn't work because there is no casetypesession in my json object
b) const target=data.Applications.casetypesession.valueOf(); (dosn't work, casetypesession is not even recognized in the variable in the dot notation)

The syntax for accessing the property of an object is:
objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]
See this reference for details.
Which in your case translates to something like this:
const target = data.Applications[casetypesession]

My own mistake, did not specify the array before the exabeam portion!
target=data.Applications[0][casetypesession];

Related

how to turn a string into a variable

Im trying to use a command for a chat program and i want to edit a variable with a command like !editvar variablehere value
so if it variablehere = '123' i want to turn '123' into just 123 or something like 'hello' into hello, in simple words im trying to make a string from a chat message into a variable name
ive tried parsing and string.raw and none worked
if(message.startsWith('keyeditvar')) {
console.log(message)
var bananasplit = message.split(' ');
var bananasplitted = json.parse(bananasplit)
console.log(bananasplitted[0].keyeditvar)
var variable = bananasplit[1]
console.log(variable)
var value = bananasplit[2]
console.log(value)
var variable2 = String.raw(variable)
console.log(variable2)
var value2 = String.raw(value)
console.log(value2)
}
i expected it to work ig
im trying to turn a string into a variable name
In Javascript, you don't usually dynamically define new variables with custom names in the current scope. While you can do it at the global scope, you cannot easily do it in the function or block scope without using tools that are generally not recommended (like eval()).
Instead, you use an object and you create properties on that object. You can use either a regular object and regular properties or you can use a Map object with some additional features.
For a regular object, you can do thing like this:
// define base object
let base = {};
// define two variables that contain variable name and value
let someName = "greeting";
let someValue = "hello";
// store those as a property on our base object
base[someName] = someValue;
console.log(base); // {greeting: "hello"}
Then, you can change the value:
someValue = "goodbye";
base[someName] = someValue;
console.log(base); // {greeting: "goodbye"}
Or, you can add another one:
let someOtherName = "salutation";
let someOtherValue = "Dear Mr. Green";
base[someOtherName] = someOtherValue;
console.log(base); // {greeting: "goodbye", salutation: "Dear Mr. Green"}
console.log(base.greeting) // "goodbye"
console.log(base[someName]); // "goodbye"
console.log(base.salutation) // "Dear Mr. Green"
console.log(Object.keys(base)) // ["greeting", "salutation"]
You can think of the Javascript object as a set of key/value pairs. The "key" is the property name and the value is the value. You can get an array of the keys with:
Object.keys(obj)
You set a key/value pair with:
obj[key] = value;
You get the value for a key with:
console.log(obj[key]);
You remove a key/value pair with:
delete obj[key]
With a plain Javascript object like this, the keys must all be strings (or easily converted to a string).
If you have non-string keys, you can use a Map object as it will take any object or primitive value as a key, but it uses get() and set() methods to set and get key/values rather than the assignment scheme of a plain object.
Please, next time put a clean code...
To convert a string to a number. You can use the function : Number(object)
So for example :
Number('123')
will return 123.
If the object value is not a correct number, it will return NaN.
So for example :
Number('hello')
will return NaN.

How to access a value within a JSON Object

I have the following JSON object notation:
[{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}]
and am unsure how to only access the "cname" value alone in JavaScript, i.e. I just require:
"www.fred.com.au"
I have tried res[0].cname but this didn't seem to work.
If you have
let object = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
then you can get that URL value via
let url = object[0]["getCname('mail.fred.com.au')"][0].cname;
The outer object is an array, and the value of the property with the long strange name is also an array, hence the [0] in two places.
This is a bit cludgy but if you don't know the 'getCname' key you can do:
let res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
let key = Object.keys(res[0])[0];
let cname = res[0][key][0].cname;
Try these
var res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
res[0] ;// returns Object {"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]};
res[0]["getCname('mail.fred.com.au')"] ;//returns Array [{"cname":"www.fred.com.au"}];
res[0]["getCname('mail.fred.com.au')"][0].cname ;//returns "www.fred.com.au"

How can I address JSON properties with complex names in Javascript?

Given a JSON object such as:
{
"#abc.def":"foo"
}
How do you address a property named like that?
e.g. this doesn't work
var x = obj.#abc.def
As #abc.def is not a valid JavaScript identifier, accessing a property with this name must use bracket notation.
The working code would be:
var x = obj['#abc.def']
It will be obj["#abc.def"] in your code.
You can use: var x = obj["#abc.def"].
Of course, I suppose that obj is defined as: var obj = { "#abc.def":"foo" }.

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:
var arrayName = new Array;
arrayName["indexName"] = value;
// i know i can also do the last line like this:
arrayName.indexName = value;
When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:
arrayName[eval("nume")] = value;
Where:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"
Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?
At first I don't think you need a real array object to do what you need, you can use a plain object.
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.
You would use objects to do that:
var hash = {}
hash["foo"] = "foo";
hash.bar = "bar";
// This is the dynamic approach: Your key is a string:
baz = "baz"
hash[baz] = "hello";
To iterate, just use a for loop or $.each() in jQuery.
use arrayName[var1+var2]
Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)
Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?
And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';
You want a plain object with the same bracket notaiton here, like this:
var arrayName = {};
arrayName["indexName"] = value;
Indeed, there was no need for an array object, a simple object did the job; further more an array introduced the need to use quotes inside the square brackets obj["var1 + var2"] to access the object property's value and not the value associated with an index (i think); the quotes transformed "var1 + var2" into a string. Using a simple object eliminated the need for quotes, so I can use obj[var1 + var2], wich worked :)
Thanks everyone !
I did something like like following;
let parentArray = [];
let childArray = [1, 2, 3];
childArray.name = 'my-array-1';
parentArray.push(childArray);
To access that by name in ES6;
parentArray.filter(x => x.name == 'my-array-1');

Categories

Resources