Javascript. Access variable values from javascript Object - javascript

I want to access a variable value of a Javascript object. The below image is a result of a console.log: console.log(variable).
I tried:
variable[0] -> returns undefined
Also tried converting using JSON.stringify -> shows '[]' on the console
Here's the screenshot of the value I want to get:

Assuming the array variable is the array of two objects, to get the string "tag1", you should try variable[0].name.

Related

Javascript - key and value in array

I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));

How do I attach JSON Stringify to a javascript variable

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

How to circumvent JSON.stringify returning undefined in a special case and that way creating an string failing for JSON.parse?

I use Windows 7 64 bit, and Firefox 32.
So I have read that JSON.parse can't handle something like JSON.parse("{ 'a': undefined }";
But when using JSON.stringify in the following context, I get undefined:
console.log("'abc': " + JSON.stringify(this.nothing));
results in
"'abc': undefined"
I'm creating my object-strings in my own functions, but for simplicity in those functions I'm using JSON.stringify for some variables.
I assumed that would bring me on the secure side.
You're using the JSON facility incorrectly:
console.log(JSON.stringify({ abc: this.nothing }));
That will give you the JSON string "{}", which is correct, because ({}).abc is undefined. The JSON spec includes no provision for undefined; the only scalar values allowed are strings, numbers, booleans, and null. Thus a JavaScript property whose value is undefined is "serialized" as not being in the object at all.
Don't use JSON.stringify() piecemeal. Create your JavaScript object structure and then stringify the whole thing.
You can't use JSON.stringify to turn values into JSON that is not supported. The value undefined is one of those values.
If you use for example JSON.stringify(null) you will get the string "null" back because that is a supported value. You can see at http://json.org/ what the supported values are.
If you use JSON.stringify(undefined) you won't get the string "undefined" back. The unsuppored value is omitted from the result, and as that makes the result completely empty (not an empty object or array), the result is the value undefined.

JavaScript objects from Eloquent JavaScript Chapter 4

JSFiddle: http://jsfiddle.net/TkV2y/3/
var chineseBox = {}; //create an object
chineseBox.content = "chineseBox"; //put a key/value pair inside chinesebox
alert(chineseBox); // why does the alert display { Object object }?
alert("content" in chineseBox); //returns true, as expected
alert("content" in chineseBox.content); //why does this alert not show up??
My questions are:
Why, when I do alert(chineseBox), do I not get the contents of the chineseBox object? I'd expected to see this:
{content: "chineseBox"}
Instead, I got [object Object] in the alert.
Why does the third alert I have there—alert("content" in chineseBox.content);—not show up?
That is the default .toString() implementation for objects in most JavaScript engines. To see the contents of the object, try: alert(JSON.stringify(chineseBox));
If you check the browser console, you'll find a type error. You cannot use the in operator on non-objects. This doesn't work (errors out): 'foo' in 'bar', but this does work (returns false): 'foo' in new String('bar')
Is the result of invoking toString upon an object Since they are objects and there is no specific format they should use, JavaScript wouldn't know how to serialize the object. If you want to see its content you need to use JSON.stringify.
The in operator searches for content inside an object. You can not search for content inside a primitive value since it has no methods or properties; hence, it will fail. You can test this by searching in a empty object; you'll see you get false as a response.

JSON object returns undefined value

I am receiving a JSON object from a http call and I am trying to extract values from it.
JSON object contains:
data:{"userid":"007", "role":"spy"}
I use the following code to assign role property to another variable followed by some console log checks:
currentUserRole = data.role;
console.log("type of data: "+typeof(data));
console.log("data: "+JSON.stringify(data));
console.log("user role: "+currentUserRole);
The logs produce:
type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined
Also I tried another method of assignment:
currentUserRole = data['role'];
But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?
According to the second line of your log (the call to JSON.stringify()), your data is actually an array of objects:
[{"userid":"007", "role":"spy"}]
If it was an object as you are expecting, it would look like this:
{"userid":"007", "role":"spy"}
(the difference is subtle, but notice the missing square brackets)
Try this:
currentUserRole = data[0].role;
Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that data is in fact an array containing at least one element.
It is a list. Try data[0].role

Categories