HI i have a problem in accessing the data in the object, my object is
profile: Object {
"-L6LmpGWAClPdVK-cqvh": Object {
"first_name": "Mithun",
"isActive": true,
"isPrimary": true,
"last_name": "N",
"phoneNumber": "123454649",
"title": "Manager",
"uid": "Vz0pWQV3UxeCbGCbaf7ld4kaNRE3",
},
"active": true,
"businessCategory": "Retail",
"companyName": "Test"
}
Now my question is :
How to access -L6LmpGWAClPdVK-cqvh values, this -L6LmpGWAClPdVK-cqvh is dynamically generated randomly key.
i can get the value of this.props.profile.email
similarly how to get the this.props.profile.-L6LmpGWAClPdVK-cqvh.first_name (Currently it says undefined)
Please help!!!
In JavaScript there are two ways to access properties in objects. Dot notation object.property and square bracket notation object['property']. Both of these work if you know the name of the property. If you have a variable that stores the name of the property or your property contains characters that are invalid for properties then you can only use the square notation.
var key = '-L6LmpGWAClPdVK-cqvh';
var value = object[key];
So in your case you would have to use this.props.profile['-L6LmpGWAClPdVK-cqvh'].first_name. The - in your random name cannot be used as a raw key, has to be a string.
The JS parser will think you are doing this.props.profile. - L6LmpGWAClPdVK - cqvh.first_name. Spaces are added for clarity.
The key in this case contains the character "-" which is preventing you from accessing through object.(dot) so instead you have to use object['string']
We can able to iterate the object. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). On iterating the object will return the keys that the object has. You can access the object values by using dot (.) notation and also by using bracket ([]) notation
for (var data in profile) {
if (data.hasOwnProperty(propName)) { //eg: propName which is first_name
var propValue = data[propName];
// do something with each element here
}
}
Related
I have two different JSON responses from ebay(); and etsy();
Etsy JSON array: [{"listing_id":123,"title":"etsy","..."}]
Ebay JSON array: [{"itemId":["123"],"title":["ebay"],..,}]
Full Ebay and Etsy JSON result shown here
Question:
1. Why are there brackets over the values of the key itemID?
2. Is it possible to combine the two arrays and display it together? Will there be additional steps to retrieve the values with/without brackets?
Etsy JSON array: [{"listing_id":123,"title":"etsy","..."}]
Here, listing_id = Integer and title = String
Ebay JSON array: [{"itemId":["123"],"title":["ebay"],..,}]
Here, itemId = array of string and title = array of string
So answer your question,
itemId is an array of string that's why it is there are brackets over the value.
Yes, it is possible to combine two arrays. You need to create the new structure to store the common values.
Accessing nested data structures
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
Here is an example:
const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};
Let's assume we want to access the name of the second item.
Here is how we can do it step-by-step:
As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:
data.items
The value is an array, to access its second element, we have to use bracket notation:
data.items[1]
This value is an object and we use dot notation again to access the name property. So we eventually get:
const item_name = data.items[1].name;
JSON Format follow some notations. In Json [] represents list of values or array of values have index in sequence 0 to length of array, {} also contains array of values but here index is called as key and these keys are any kind of string or random number.
Here in question "itemId":["123"],"title":["ebay"] values of both itemid and title are list of values. So while accessing you need to specify which value you need to display. like itemId[0] which return first value. In case no list of values you can directly access it using itemId.
Yes you can combine 2 array and display together. It depends on your logic of combine.
Example:-
Etag = [{"listing_id":123,"title":"etsy","..."}]
Access It as:-
Etag[0].listing_id #123
Etag[0].title #etsy
Etag = [{"listing_id":[123],"title":["etsy"],"..."}]
Access It as:-
Etag[0].listing_id[0] #123
Etag[0].title[0] #etsy
Im trying to find the length of the report_data(object) key using the below code..but for some reasons it yields value 3.
a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"}
Object {report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"}
Object.getOwnPropertyNames(a.report_data).length
3
for more clarity I have the image.
a.report_data is a string with three properties:
0, representing the first character ("{").
1, representing the second character ("}").
and length, representing the length of the string (2).
It's a little counter-intuitive, if you come from other languages, that 0 and 1 are properties, but in Javascript array elements are properties just like all other properties, and "regular" properties can be accessed using array syntax (aka "bracket notation"):
// "array elements"
a.report_data[0] === "{";
a.report_data[1] === "}";
// or...
a.report_data["0"] === "{";
a.report_data["1"] === "}";
// "normal" properties
a.report_data.length === 2;
// or...
a.report_data["length"] === 2;
These are all property names, and, thus, when you ask for an array of property names for your string, you get:
["0", "1", "length"]
Assuming you want the length of the actual string value, then you simply want to use report_data.length, as demonstrated here:
var a = {
report_freq: "daily",
report_item_num: 2,
report_num: 39,
report_data: "{}"
};
console.log(a.report_data.length)
Your current code includes this:
Object.getOwnPropertyNames(a.report_data).length
If you look at the docs for Object.getOwnPropertyNames(obj), you'll see the following description:
Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly upon obj.
So, in this case, Object.getOwnPropertyNames(a.report_data) returns an array containing the keys found on the string, and there happens to be 3 of them.
I was following this article (https://www.visualstudio.com/docs/integrate/extensions/develop/add-dashboard-widget) to create a widget to add it to microsoft dashboard.
In my html file, there is this piece of code that I cannot get to work:
...(some code above)
return TFS_Wit_WebApi.getClient().getRevision(284,6)
.then(function (query) {
var $list = query.rev;
var $container = $('#query-info-container');
$container.empty();
$container.append($list);
... (some code below)
In this line:
var $list = query.rev;
I'm trying to get access to .json file "rev" variable.
Here is my .json file
{
"count": 15,
"value":
[
{
"id": 284,
"rev": 1,
"fields": {
"System.WorkItemType": "User Story",
"System.State": "New",
"System.Reason": "New",
"System.CreatedDate": "2016-06-23T14:31:37.567Z",
},
...(some code below)
And I'm able to get access to this "rev" variable.
However, now I want to get access to "fields", namely to
"System.State": "New",
Instead of
var $list = query.rev;
I tried
var $list = query.fields.System.WorkItemType[0];
And
var $list = query.value.fields[0];
and
var $list = query.fields;
However, that did not work.
Here is some documentation on how it is supposed to be accessed
fields: {[key: string]: any}.
But it is not much of a help.
Any help will be greatly appreciated!
Thank you!
You can use JSON objects as a kind of "map", what means they are composed of key-value pairs.
var $list = query.fields['System.State'];
There are many different ways of accessing a JSON object properties, as you have already mentioned in your question. However, if the property contains a dot or a space on its name, you need to fall back to the array notation. This means that the following attempts will yeld the correct result:
query.fields
query[fields]
query.fields['System.State']
query[fields]['System.State']
But the ones below will not:
query.fields.System.State
query[fields].System.State
This happens because, in the last two ways, JavaScript will think you are trying to access the State property of the query.fields.System object (which does not exist).
The same applies for objects that have a property whose name contain spaces. Accessing them as object['my property'] will work, but using the dot notation with object.my property will not.
Additional questions regarding this can be seen here:
Dot Notation and Square Bracket Notation in JavaScript
JavaScript property access: dot notation vs. brackets?
What is reason of using ' [ ] ' notation to access javascript object members instead of dot notation?
Try this:
var $list = query.fields["System.WorkItemType"];
JavaScript will interpret the System and WorkItemType as nested properties because of the dot.
Access to json elements is very easy:
1º Create a new var to transform the json data to a new object. Really json has the javascript object format.
var data = '{ "count": 15, "value": [ {"id": 284, "rev": 1, "fields": {"System.WorkItemType": "User Story", "System.State": "New", "System.Reason": "New", "System.CreatedDate": "2016-06-23T14:31:37.567Z", }, ...(some code below) '
var json = JSON.parse(data);
2º Access to a specific element of the object via “.” or “[]”:
Dot notation:
var json.value[n].fields['System.State'];
Note that you can use dot notation with System.State key.
[] notation:
var json['value'][n]['fields']['System.State'];
being n the index to access to a specific element of your object array
This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined
I am trying to figure out if I JSON.Stringify an object like this:
{"m_id":"xxx","record":
{"USER":"yyy","PWD","zzz","_createdAt":
11111."_updatedAt":00000},"state":"valid"}
and then try to JSON.Parse out only the USER and PWD, not have to just call the object, but go through stringify. how would that work?
thanks.
I'm not sure why you're talking about stringifying your object. You'd stringify it if you needed to send the data across a network or something, not when you need to manipulate it in JS.
...how do I extract the strings in {...USER: "aaa", PWD: "zzz"...}?
Assuming you have a variable referring to the object, something like the following (with or without nice line breaks and indenting to make it readable, and with or without quotes around the property names):
var obj = {
"m_id": "xxx",
"record": {
"USER": "yyy",
"PWD" : "zzz",
"_createdAt": 11111,
"_updatedAt": 00000
},
"state": "valid"
};
Then you can access the properties in the nested record object as follows:
console.log( obj.record.USER ); // outputs "yyy"
console.log( obj.record.PWD ); // outputs "zzz"
// etc.
(Note: in your question you had two typos, a comma that should've been a colon in between "PWD" and "zzz", and a dot that should've been a comma in between 11111 and "_updatedAt". There's no way that JSON.stringify() would have produced the string that you showed with those mistakes.)
If you want the strings "USER", "PWD" etc as an array, then use Object.keys.
If you want to iterate them, just use a normal for-in enumeration.
I might have misunderstood the question, but if I think it is what it is then try using
var tmp = JSON.parse(string_to_convert)
this should suffice to convert your string to a proper Javascript Object
Then you can do
for(var index in tmp){
console.log(tmp[index]);
}
and this should list all the keys on the first set of properties. If you want to do a nested thing, then use recursion on the properties. Hope this makes sense...