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"
Related
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];
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.
Hey guys I noticed something strange today with trying to set a key value pair in JavaScript. I know that The Key of an object is always 'stringified' so that the key value pair is always string: value, however something strange happened today when I tried this with an array. Example below:
var ob = {};
var a = [2,4];
ob[a] = 10;
console.log("this is ob ", ob);
Here I have tried adding the key [2,4] to map to 10. However, the console log returns the string 2,4 mapping to 10 instead of the string [2,4] mapping to 10. Does anyone know why this happens?
Using an object or an array as the property name, doesn't invoke JSON#stringify, but the object's toString method, which in arrays returns the array elements joined by a comma.
In the example I override the Array#toString method, and you can see that the resulting property name reflects that:
var ob = {};
var a = [2,4];
a.toString = function() { return 'cats' }; // override toString
ob[a] = 10;
console.log("this is ob ", ob);
I am using express.js and the cookie-parser middleware. I am trying to use a function to push the cookie name and the cookie value into an array.
I want the array to end up looking like the following:
loop = [{cookie1: value1}, {cookie2: value2}];
But for some reason when I push the key and the value into the array, the key is just being assigned as a string called key, instead of the actual value set in the function. So my array ends up looking like the following:
loop = [{key: value1}, {key: value2}];
I define the variable 'key' inside the function, and if I console log it inside the function it is set to the right value (i.e cookie1), but for some reason when I try to push it into the array, it just pushes in 'key' instead of the actual variable.
Below is the full function, any ideas would be greatly appreciated. Thanks.
var loop = [];
cookie_objects(req.cookies);
function cookie_objects( cookies ) {
for (var cookie in cookies) {
if ( cookie != 'seen_cookie_message' && cookie != '_ga' ) {
var key = cookie;
var value = cookies[cookie];
loop.push({key : value});
}
}
}
You have to create the blank object beforehand - then assign the key via bracket notation:
var obj = {};
obj[key] = value;
loop.push(obj);
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');