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.
Related
I have two variables with JSON files. The first is a list of keys looks like this:
keylist = ["key1","key2","key3"]
The second one is generated from a database and looks like this:
data = {
"key1"{
#further data
},
"key2"{
#further data
},
"key3"{
#further data
}
}
Now I want to access the second element of the database with the key from the keylist
data.keylist[1];
Which doesn't work because the return of keylist[1] is a String? I did some research and the use of the window function was proposed. So I tried this:
window["data." + keylist[1]]();
Which leads to a "is not a function" error. What can I do to solve this problem?
As simple as that:
const mydata = data[ keylist[1] ];
Also, your code is correct from the point of syntax, but it tells completely different than you expect it to tell.
data.keylist[1];
tells JS that you expect to have an object called data which has a property called keylist and which is (most likely) type of array, and you want to get the second element of this array.
PS: And one more point here. Your question title is not completely correct because of the difference between Arrays and Object in JS.
There is no "string keys" for arrays in JS, so you cannot "access array with a string key". Well, truly speaking there are, but not for items of array. Array items only have numeric index, which you can use to access it. Objects, in contrast to arrays, may have named properties. So when you see something like that: data = myVar['data'], you can tell that you're dealing with an object, while data = someVar[0] can be both, an Array (most likely) or also an Object with key named '0'.
I don't think the issue you're having with your first example is because it returns a key. I believe the issue is because data doesn't have a property called keylist. Instead of that, try it as
data[keylist[1]]
and see if that works for you. The reason this one should work is that, in this situation, Javascript will evaluate the string return of keylist[1] and then use it as a string index for the data variable. Let me know if this works out for you :D
You can try using using something like this.
data[keylist[1]]
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.
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.
I'd like to save a DOM element in a object. But not as a value, i want save it as a key of the object. But i think the core of javascript is not able to do that.
data={}
data[$('div#a')] = 'A';
data[$('div#b')] = 'B';
console.log(data[$('div#a')]); //return B
Do you know some way to save the element in a index object?
Imagine i have XXXXXX elements on my document. If i want to access to the element properties when some event happen on it i dont want to iterate XXXXXX elements to find it.
Why i don't use data of jquery for two reasons:
I want to do it on native javascript
I dont want another array to iterate separate data from the elementid
So the perfect way to do it was have only one object with the elements on the key to acces them easy. And if i want iterate them i only have to do for i in data
JavaScript objects will only accept strings as keys, and JS will use .toString() if you try to use anything else as a key, typically resulting in everything being stored under the (single) key "[object Object]".
Is there any reason you can't use $('#a').data() to store the data associated with that element directly on the element?
Failing that, assuming that every such element has an ID, just use the element ID as the object key.
NB: ES6 has a Map object which can use arbitrary keys, but that's only an experimental feature in current browsers. However even then you would have to use the actual element as the key rather than a jQuery wrapped $(element) object, since $('#a') !== $('#a') - you would have to use the exact same original jQuery object each time you access the map, not a newly constructed object.
Javascript objects only accept string as key.
So if you try to give key value other than string, javascript will internally call .toString() method of that object and use return value of it as key.
Object keys have to be stings.
You can use the data method to associate anything to the element:
$('div#a').data('name', 'A');
$('div#b').data('name', 'B');
console.log($('div#a').data('name')); //return B
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;