Access fields in an array contained in a model - javascript

I have some JavaScript code that needs to be able to access fields of an array of objects that is contained within my model. I currently have this:
var model = #Html.Raw(Json.Encode(Model));
for(var i = 0; i < model.testobject.length; i++) {
console.log(model.testobject[i]);
}
Which prints out the fields within each object of testobject. But say I have a field, ID, in my testobject class. How do I then access that? Doing this:
console.log(model.testobject[i].ID);
Does not work. Do I have to somehow encode that specific instance of testobject before accessing it's fields?
And yes, before anyone says it I know this should be contained within the controller. As it currently stands though, that's not possible for this project.
This is the general structure of what is printed out:
Object {field: value}
Edit:
I attempted to use JSON.stringify on my model.IdentifiApprovalConfigurations and it seems I got a little close to reaching my solution. This is what it looks like now:
console.log(JSON.stringify(model.testobject[i]).ID);
However, this prints out undefined.
Edit 2:
Oops, seems the ID field I'm trying to access isn't being populated before I send them to my view which is my own issue. JSON.stringify works though, and I understand why it wasn't working earlier.
Final edit:
JSON.parse(JSON.stringify(model.testobject[i])).Value
I had to stringify and then parse my JSON to access the value.

As I'm still starting out with web development, I forgot that I needed to convert my object into a JSON object. This:
JSON.parse(JSON.stringify(model.testobject[i])).Value
Is the final piece of code that allows me to stringify an object, parse the JSON and then access fields within that object.

Related

Access Array with String key

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]]

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.

Parsing incoming JSON in JavaScript - what happens to the "extended parameters"?

I am attempting to parse the incoming JSON from XBMC (Eden Beta v3), an example string from XBMC is as follows:
{"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":""},"sender":"xbmc"}}
I am using json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js to give me the JSON.parse and JSON.stringify functions in my application.
I am using the parse function in my code like this
var temp = JSON.parse(data);
Which is working fine for the first two properties, "jsonrpc" and "method"... so I can access those like this
temp.method
returns "Player.OnPlay"
temp.jsonrpc
returns "2.0"
However, if you look at the string sent by XBMC, it also contains what they refer to as "extended parameters" or "params", I cannot seem to track down what the JSON parser is doing with the rest of the message, or how I can access them in similar ways as the first two properties. If I try
params = temp.params
or any other way of accessing the params property, I get an Undefined error as there is no such property in the JSON object... I hope this is clear enough for someone to take a stab at helping me out. Will provide any extra info needed...
Thanks
The value of params in the JSON data is an object, so you have to access the sub-properties of that.
temp.jsonrpc
temp.method
temp.params["data"]["item"]["type"]
temp.params["data"]["player"]["playerid"]
temp.params["data"]["player"]["speed"]
temp.params["data"]["item"]["title"]
temp.params["sender"]

JavaScript json value

I have a JSON var response (See below) but I can't retreive the value of "reputation" using response.users[0].reputation. I am in Dashcode and it says in error Result of expression response.users[unknown] is not an object. What is the correct syntax?
edit: The variable is dynamically loaded from a XMLHttpRequest. A static var with same json is working.
I guess from XMLHttpRequest you recieve string but not json object, so you need parse it first in order to get json object, for example using JSON.Parse or jQuery.parseJSON and response.users[0].reputation should work.
The JSON is fine. I just checked it and "response.users[0].reputation". (Second pair of eyes and all that.)
I would be more concerned about the "unknown" in "response.users[unknown]". It doesn't look like you are requesting the 0th index of the array "users". Something's going wrong there.
Personnally when i test the syntax of your Json, it is correct :
http://www.jsonlint.com
I have just deleted the comment "//need to get its value".
Your code works for me as you have done it. Maybe you are not assigning the variable correctly (var response = {"total": 1, etc...) or have a typo somewhere

Categories