Get value in data object Javascript - 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.

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.

Access fields in an array contained in a model

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.

Check passed data with a view is not empty in laravel

I am using laravel 4 and I want to pass a data with a view.
I have used this code in a controller.
$view = View::make('settings.editEvent');
$view->bounderyData = $bounderyData;
And I want to check whether this data exists or not in the view settings/editEvent.blade.php
Tried using this..
<script>
if('{{$bounderyData.length()}}'!=null)
console.log('exists');
</script>
Error :
Array to string conversion error
How can I check the existence ?
Do not assign the data to the View variable, but instead, pass it along using with as Laravel requests you to use:
$view = View::make('settings.editEvent')
->with('bounderyData', $bouderyData);
Actually both of the snippets work the same way. You can either pass data using with() method or by assigning it to view as property. So it doesn't really matter. But it looks like you are using some weird syntax because you are trying to access method length() using dot syntax inside Blade echo statement. Try:
if({{count($bounderyData)}}!=null)
console.log('exists');
or something similar. Remember that everything inside {{}} is going to be echo'ed by PHP. So if you have some sort of array there you may either want to count number of elements or maybe cast it to JSON and then decode it inside Javascript. If you still have problem, let us know what is the issue.

Javascript: Using a string to acces objects property

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

Categories