Javascript: Using a string to acces objects property - javascript

If I have a string like
var s = someString;
But I do NOT know the value of that string, since the program obtains it from external file, and I wanted to use that string to access an objects property, like:
alert(obj.s)
//or
alert(obj[s]);
How would I do that? The code I wrote doesn't work, the alerts are just empty (and I'm positive that s is NOT empty AND that there is a property with the same value as s). But when I try to access an object normally it works fine (using a property name I already know):
alert(obj.name);
//or
alert(obj["name"]);
So...any ideas? Thanks

Related

How do I access the 'str' value in my object?

I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.

Get value in data object Javascript

I have a data object, and i want to get on of the value from it, when i try to print the data:
console.log(data);
i got an object like the image below :
the problem is i want to get the order[billing_address][country_id] which i think is an object, but i don't know how to fetch it. i've tried :
console.log(data.order); //didn't work
console.log(data.order[billing_address][country_id]);//didn't work
The name of the property is: "order[billing_address][country_id]"
To access its value try:
console.log(data['order[billing_address][country_id]'); // Should work
It appears that the values you are looking for have keys that are the whole string:
"order[billing_address][telephone]"
You can access these values like this:
data["order[billing_address][telephone]"] //"5"
You are currently trying this:
data.order[billing_address][country_id]
What you are trying doesn't work because there are no variables billing_address or country_id that are defined, and the object is not that deeply nested - just has the above mentioned long string for a key.

Accessing response data using Angular.js with numerical named field

My response object has a field called "50", so right now I'm trying to access and save that data doing something like this:
var thing = $scope.data.array[0].50;
However I'm getting an error on the console when I simply reload the page with the function not even running. When I get rid of the 50, everything is fine. There is indeed a field called "50" inside the $scope.data.array[0] and I do not have access to change the response. Is there something wrong with this because the field is called "50" and maybe JS is interrupting that as a number instead??
Also when I changed "50" to something random like "af", then I get no errors on refresh.
this doesn't work
var thing = $scope.data.array[0].50;
this works
var thing = $scope.data.array[0].af;
The following should work if your first element of the array has a property called "50".
var thing = $scope.data.array[0]["50"];
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Syntax
object.property
object["property"]
JavaScript objects are also associative arrays (hashes). Using these you can associate a key string with a value string as shown in the example above.
The reason as to why you don't get an error when accessing $scope.data.array[0].af; is because "af" is valid identifier for a property. Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence.
For all other property names, you must use bracket notation.

Javascript Objects and keys

The following command shows the properties of an Object.
var keys = Object.keys(result);
Output: [requester.client.id,request.id]
When I try to print an alert(result[request.id]) or alert(result.request.id) I dont get the values. Is there something I am missing?
In JavaScript objects keys are strings, though they can have periods. What you probably getting as the output is ['requester.client.id','request.id'], so it should be accessed as result['requester.client.id'].
Your result object has properties named "requester.client.id" and "request.id".
You need to do alert(result["request.id"]).
result[request.id] does not work because request here is treated as a variable name, and you probably have no variable named request.
result.request.id is closer, but it also fails because the property name has a period in it, so the parser treats this as the the id property of the request property of result.

Javascript objects with JSON

Im sure this must have been asked before but I can't find an example on SO.
I have a JSON string that starts out life as something like this:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}}
The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.
So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.
function changeJSON(node, value) {
json = JSON.parse($('#json').val());
json.selection[node] = value;
delete json.changed;
json.changed = {node:value};
$('#json').val(JSON.stringify(json));
}
"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) I.e. if I called the function with changeJSON("BC","HC") the JSON string becomes:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}}
I understand what javascript is trying to do but I want the changed element to be what my variable contains i.e.
,"changed":{"BC","HC"}
and not
,"changed":{"node","HC"}
I'd love someone to tell me what I am doing wrong!?
EDIT
Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.
I don't think this is the same question, mine is why the literal variable name is used rather than the contents of the variable
The question referenced explains how to resolve the issue, but since you are asking for an explanation.
A variable name is a JavaScript identifier.
A property name in object literal syntax is also a JavaScript identifier (although you can use a string literal instead).
Since an identifier cannot be both a variable and a property name at the same time, you cannot use variables for property names in object literal syntax.
You have to, as described in the referenced question, create the object and then use the variable in square bracket notation.
The solution, as Quentin suggested is to create th object first i.e.
delete json.changed;
json.changed = {};
json.changed[node] = value;

Categories