JS Symbol as object key - javascript

I'm running a node software where in a certain context of the software there is an object which one of it's keys is a Symbol, and it's value is an object. For example:
object = {Symbol(symbol_name): another_object}
I'm trying to get to the 'another_object' keys and values and can't find the way to do so. Suggestions anyone?

The best approach would be to save the Symbol in a variable first, then just use bracket notation to look it up:
const sym = Symbol('symbol_name');
const object = {[sym]: { foo: 'bar' }}
console.log(object[sym]);
If you don't have a reference to the symbol, and the object contains only one symbol, you can get it with getOwnPropertySymbols:
const object = {
[Symbol('symbol_name')]: {
foo: 'bar'
}
};
const sym = Object.getOwnPropertySymbols(object)[0];
console.log(object[sym]);

Put the object key in brackets like this:
object = {[Symbol(symbol_name)]: another_object}

Related

Object keys - Javascript: why doesn't work to create object inside object?

I don't know if I am mind-collapsed or just need to work harder with objects, but I don't get why this doesn't work:
const obj = {};
const obj['pagination']['searchword'] = searchWord;
It says:
Cannot set property 'searchWord' of undefined
It looks like I can't create that kink of object:
console.log(obj)
{
pagination:{searchWord:valueOfSearchWordVariable}
}
I tried to with const obj.pagination['searchword'] = searchWord;
If you want to create an object inside an object, you have to define the object explicitly somewhere. If you try to access a property of an object as if it was a nested object, one won't automatically be created.
For your case, it would be easier to define the object all at once, in one statement, not two:
const obj = {
pagination: {
searchword: searchWord
}
};
If you have to assign after object initialization, then you'd do:
obj.pagination = {
searchword: searchWord
};
If you change the searchWord variable name so it matches the lower-case property name, you can use shorthand notation:
obj.pagination = {
searchword
};
You have to define obj['pagination'] first. Now you are assigning to an undefined.
obj is an empty object. But what is obj['pagination']? it is not set yet. And while obj['pagination'] is not set you are trying to assign a property to it.
you also can assign an empty object.
obj['pagination'] = {};
and then you can do this.
obj['pagination']['searchword'] = searchWord;
Another way to do this
Object.defineProperty(obj, 'pagination', {
searchword: searchWord
});

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.

JavaScript: Stringify actual variable name

I'm currently running a series of functions where the first argument is a variable defined elsewhere, and the second argument is a string that happens to be identical to the variable name:
assignString(Hello, 'Hello')
assignString(World, 'World')
assignString(Foo, 'Foo')
assignString(Bar, 'Bar')
...
Ideally I would like to simplify this to something like this:
['Hello', 'World', 'Foo', 'Bar'].forEach(() => { assignString... })
or
[Hello, World, Foo, Bar].forEach(() => { assignString... })
Is this actually possible?
const vars = { Hello, World, Foo, Bar };
Object.keys(vars).forEach(key => assignString(vars[key], key));
I think the only way you could dynamically create variables based on a string value is by doing something like this:
var exampleStringValue = 'HELLO';
window[exampleStringValue] = exampleStringValue;
console.log(window.HELLO);
// or, since window is the global context in the browser
console.log(HELLO)
I honestly can't say I can dream up a use-case where that's a good practice, but I don't know your use-case, so no judgement here :)
I'd also like to point out this little library that I've found useful for creating objects where the keys have same value as the name of the key: https://github.com/STRML/keyMirror. I've found that to be used pretty heavily in the React community.
Since the variable name and the string are equivalent, there's no need to pass it in twice. I'd rather pass in the scope of the variable. You could do this so it works in whatever scope you're in:
function assignString(scope, val){
scope[val] = val;
}
Called like
assignString(window, "Hello");
Output of console.log(Hello) ==> "Hello"
Using the new ES6 Map object, we can create name/value pairs in a structure that can then be turned into an Array, so forEach can work:
// Variables that assignString will need:
var Hello = "var1", World = "var2", Foo = "var3", Bar = "var4";
// Map object that contains name of variables and strings that match variable name
var m = new Map([[Hello, "Hello"],[World,"World"],[Foo, "Foo"], [Bar, "Bar"]]);
// Turn Map into Array so forEach will work:
var a = Array.from(m);
// Call forEach which calls assingString and passes key name
// (variable name) and string value
a.forEach((value) => { assignString(value[0], value[1]); });
See this fiddle: https://jsfiddle.net/qnwsajes/34/
You can create an object with your data, iterate over the keys, and pass the key-value-pair to your assignString function.
var data = {
Hello: Hello,
World: World,
Foo: Foo,
Bar: Bar
}
Object.keys(data).forEach(key => assignString(data[key], key));

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!

How to access the properties of a JavaScript object?

while review a javascript coding, i saw that
var detailInf = {
"hTitle":"Results",
"hMark":"98"
};
What's the concept behind this js coding. While give alert for the variable its shows as "[object Object]". So this is an object, then how can we access the variable and reveal the data from this object.
Try doing this:
alert(detailInf['hTitle']);
alert(detailInf.hTitle);
Both will alert "Results" - this is a Javascript object that can be used as a dictionary of sorts.
Required reading: Objects as associative arrays
As a footnote, you should really get Firebug when messing around with Javascript. You could then just console.log(detailInf); and you would get a nicely mapped out display of the object in the console.
That form of a JavaScript object is called an object literal, just like there are array literals. For example, the following two array declarations are identical:
var a = [1, 2, 3]; // array literal
var b = new Array(1, 2, 3); // using the Array constructor
Just as above, an object may be declared in multiple ways. One of them is object literal in which you declare the properties along with the object:
var o = {property: "value"}; // object literal
Is equivalent to:
var o = new Object; // using the Object constructor
o.property = "value";
Objects may also be created from constructor functions. Like so:
var Foo = function() {
this.property = "value";
};
var o = new Foo;
Adding methods
As I said in a comment a few moments ago, this form of declaring a JavaScript object is not a JSON format. JSON is a data format and does not allow functions as values. That means the following is a valid JavaScript object literal, but not a valid JSON format:
var user = {
age : 16,
// this is a method
isAdult : function() {
// the object is referenced by the special variable: this
return this.age >= 18;
}
};
Also, the name of the properties need not be enclosed inside quotes. This is however required in JSON. In JavaScript we enclose them in brackets where the property name is a reserved word, like class, while and others. So the following are also equivalent:
var o = {
property : "value",
};
var o = {
"property" : "value",
};
Further more, the keys may also be numbers:
var a = {
0 : "foo",
1 : "bar",
2 : "abz"
};
alert(a[1]); // bar
Array-like objects
Now, if the above object would have also a length property, it will be an array like object:
var arrayLike = {
0 : "foo",
1 : "bar",
2 : "baz",
length : 3
};
Array-like means it can be easily iterated with normal iteration constructs (for, while). However, you cannot apply array methods on it. Like array.slice(). But this is another topic.
Square Bracket Notation
As Paolo Bergantino already said, you may access an object's properties using both the dot notation, as well as the square bracket notation. For example:
var o = {
property : "value"
};
o.property;
o["property"];
When would you want to use one over the other? People use square bracket notation when the property names is dynamically determined, like so:
var getProperty = function(object, property) {
return object[property];
};
Or when the property name is a JavaScript reserved word, for example while.
object["while"];
object.while; // error
That's an object in JSON format. That's a javascript object literal. Basically, the bits to the left of the :'s are the property names, and the bits to the right are the property values. So, what you have there is a variable called detailInf, that has two properties, hTitle and hMark. hTitle's value is Results, hMark's value is 98.
var detailInf = { "hTitle":"Results", "hMark":"98"};
alert(detailInf.hTitle); //should alert "Results"
alert(detailInf.hMark); //should alert "98
Edit Paolo's answer is better :-)
As Dan F says, that is an object in JSON format. To loop through all the properties of an object you can do:
for (var i in foo) {
alert('foo[' + i + ']: ' + foo[i]);
}

Categories

Resources