get data from array object in javascript - javascript

I am trying to get data from an object. I have tried to get the data as a.doc._id as given below.
function ab(data){alert("content is "+data.doc.id);}

You probably need to access the property using the square bracket notation. Try -
alert("sdf" + data["doc._id"]);

"doc" is not an object, as shown in the inspector, you should rename the property name to something like doc-title instead.
Otherwise, you should create the object something like this
var data = {
"act" : "",
"doc": {
"_id" : "9",
"title": "fghfgh"
}
};

Related

Accessing fields in .json file

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

Javascript- get property starting with single quotes [duplicate]

I have a very simple array (please focus on the object with "points.bean.pointsBase" as key):
var mydata =
{"list":
[
{"points.bean.pointsBase":
[
{"time": 2000, "caption":"caption text", duration: 5000},
{"time": 6000, "caption":"caption text", duration: 3000}
]
}
]
};
// Usually we make smth like this to get the value:
var smth = mydata.list[0].points.bean.pointsBase[0].time;
alert(smth); // should display 2000
But, unfortunately, it displays nothing. When I change "points.bean.pointsBase" to something without dots in its name - everything works.
However, I can't change this name to anything else without dots, but I need to get a value? Is there any options to get it?
What you want is:
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
Try ["points.bean.pointsBase"]
If json object key/name contains dot......! like
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
myJson["my.name"]
myJson["my.age"]

How to access an attribute from a JSON line saved in a position from an 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

Retrieving value from nested Javascript Object

I'm scratching my head here why I can't figure this out. It should be easy. I am trying to work with a Javascript object which looks like so:
Object {object: "clip", function: "list", data: Object, items: 1} (console log )
This Object is stored in a variable called data.
if I do var items = data.items I get the number I expect (1). What I cannot seem to get is what is in the data section.
The data.data logged to the console looks like this:
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"…}
I would expect if I wanted the Clipid I would be able to do:
var Clipid = data.data['Clipid'] or data.data.Clipid; however this always comes up null.
I've tried a number of things, but nothing works. I'm sure it's something silly or small I'm missing but any insight is appreciated. Thanks!
If it helps the data comes from jQuery.parseJSON( jsonString )
Note ** If I do this:
var objd = data['data'];
var arv = $.map(objd, function (value, key) { return value; });
I am able to get values like arv[0] etc but I'd prefer to go by key if possible...
Note 2 - It's the JSON Formatting I'm decoding
Hey sorry about this, I noticed the encoding is borked. It looks like if I do:
console.log( data.data["\u0000Clip\u0000id"] ); it wotks! It must have to do with the json_encode.
There's a small typo I guess-
data.data.Clipid
note the small i
It looks like the data is an object, not a dictionary, so you would do var Clipid = data.data.Clipid; to get at the information inside.
You can't do data.data['Clipid'] because you named the attributes using string literals, and the proper syntax you used (data.data.ClipId) has a typo, as mentioned.
if your "Object" in the "data" variable, you just have to do
var clipid = data.Clipid;
var object = {object: "clip", function: "list", data: {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}, items: 1}
console.log(object);
Object {object: "clip", function: "list", data: Object, items: 1}
console.log(object.data)
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}
console.log(object.data.Clipid)
1
This works fine for me, we would need to see your code to see why you are specifically having problems.
It had to do with the JSON encode method in PHP... All the answers stated was what I had tried and are correct, it was just a valid JSON string which had had unexpected unicode characters.
To fix it I needed to do this: $json = str_replace('\u0000', "", json_encode( $response )); Where response was my array of data to be cnverted

Create dynamic nested list from JSON using jQuery

I have a problem understanding this problem. I have this json in a file called list.json for testing purpose. I will be getting this list generated by server later on.
[
{
name : "ABC",
id : "link_abc"
},
{
name : "DEF",
id : "link_def"
},
{
name : "GHI",
id : "link_ghi"
},
{
name : "JKL",
id : "link_jkl"
}
]
And here's my javascript to display the list in <li> format.
$(function(generate_list_from_JSON){
$('a[href="#state"]').click(function(){
$.getJSON("scripts/list.json", function (obj){
$.each(obj.name, function (key, value){
alert(key);
})
});
});
});
The problem is, there's nothing displayed, even in console. How do I trap what's sending and what's receiving? I tried console.log() but still blank.
JSON requires quotation marks around the attribute names. So you need to do something like this:
[
{
"name" : "ABC",
"id" : "link_abc"
},
...
]
JavaScript objects don't require the attribute names to be quoted, but JSON does.
HTH
I see few problems:
Your JSON object is invalid. It is an array of objects but first two objects are not separated with , and strings in JSON should be quoted.
In your javascript code, you are refering to obj.users, and your object, even if it would have that ,, does not have users at all.
You cannot do an each on obj.name. obj is an array. Arrays do not have a property named "name" and therefore you'll never enter the loop.
Just loop through obj[0] to obj[obj.length-1].

Categories

Resources