How do I access this JSON data in Javascript? - javascript

{"0":
{"id":"276","course":"92","name":"Tutorial - Compound Measures",
"activitylink":"2490","available":"1331231400","deadline":"1331235000"},
"1":
"example#gmail.com","reference":"example#gmail.com"}
I am trying to access this in jQuery/Javascript but I unable to. This is my jQuery:
$('#lessonSelect').live('change', function()
{
$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data)
{
var len = data.length;
var lessonDialog = "";//initialise
var launchLessonDiv = 'Launch Lesson';
for (var i = 0; i< len; i++)
{
lessonDialog += '<p>' + data[i].name + '</p>'; //get lesson name
}
$('#lessonDialog').html(lessonDialog); //insert lesson name into dialog
$('#launchLessonDiv').html(launchLessonDiv);
});
});
This is basically for a select list. Each time the user selects something, links and other stuff on the page change. The stuff works when the page is first loaded but when I start selecting stuff in the select list the lessonDialog comes up blank with nothing inside it.

Convert the object with numeric keys to a true array:
$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data) {
data = Array.prototype.slice.call(data);
Your current method fails, because { ... } results in the creation of an object, not an array. The length property of the object is undefined, so the loop would never get started:
for (var i=0; i<undefined; i++) ; // <-- 0 < undefined is always false

Related

Refreshing a variable when records deleted from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display the localStorage records:
// get localStorage info
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
// get localStorage length
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
// assign variables for HTML ID elements
var list_items = document.getElementById("usernames");
var plaintext_textarea = document.getElementById("plaintext");
// assign a MyUsernames variable
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
// if localStorage length > 0
if (jpxun_length > 0) {
// loop through localStorage
// get the word part of the username and wrap in list item HTML
// add a link in the list item to delete the localStorage ite via 'deleteById'
for (var i = 0; i < MyUsernames.length; i++) {
// assign a variable to hold the username
var un1 = MyUsernames[i].name;
list_items.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#' onclick='deleteById(this)'>" + un1 + "</a></li>";
// build plaintext version of username list
plaintext_textarea.innerHTML += un1 + "\n";
}
}
// function to delete records from localStorage
var deleteById = function ( self ) {
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
// try to re-do plaintext content
var jpxun2 = JSON.parse(localStorage.getItem('jpxun')) || [];
var MyUsernames2 = JSON.parse(localStorage.getItem("jpxun2"));
for (var i = 0; i < MyUsernames2.length; i++) {
var un1 = MyUsernames[i].name;
plaintext_textarea.innerHTML += un1 + "\n";
}
}
I realise that's a bit of code overload...
Basically it all works - the thing I can't get to work is that when I delete a record from localStorage, e.g. by clicking HTML for a list item for a word, which might look like this:
<li><a id="1" href="#" onclick="deleteById(this)">tippins</a></li>
Then the record is deleted from localStorage, and div id usernames containing the words as list items is automatically refreshed, as the deleted record is removed.
However, the list of words in the textarea is not refreshed (even though it is built up from the list of items in localStorage).
Here's what I tried to refresh the textarea list of words when a word is deleted from localStorage in the deleteById function:
// try to re-do plaintext content
var jpxun2 = JSON.parse(localStorage.getItem('jpxun')) || [];
var MyUsernames2 = JSON.parse(localStorage.getItem("jpxun2"));
for (var i = 0; i < MyUsernames2.length; i++) {
var un1 = MyUsernames2[i].name;
plaintext_textarea.innerHTML += un1 + "\n";
}
However - that doesn't work, and the textarea list is not updated and the deleted words still appear in that.
The only way the textarea list is updated is when the page reloads, but I'd like to have the list automatically update when a record is deleted from localStorage, in the same way the list items are automatically updated.
I'd simply create a function with a single responsibility to render the content of the textarea based on the data stored in the localStorage, like below
function renderTextArea() {
let data = JSON.parse(localStorage.getItem("jpxun")) || [];
let content = data.map(u => u.name).join("\n");
plaintext_textarea.innerHTML = content;
}
and then just call this function in your deleteById.

Parse JSON from url to use in html

i have a json file in an url that appears like this
[{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false},
{"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]7
I want to parse it, either through javascript and use it to display the tier, rank and leaguepoints in html.
I'm new at this, and I cant figure out how to parse the json into usable variables to display in the html file. please help if u can.
You can use jquery to get the json from url
$.getJSON('http://myurl', function(data) {
for(var i = 0, len = data.length; i < len; i++) {
var obj = data[i];
//obj will be your item with obj.tier, obj.leagueName etc.
}
});
Refer to the question How to get JSON from URL in Javascript for accessing the data from the URL. Then you can iterate through the data with a loop:
var data = [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false}, {"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]
for (var i = 0; i < data.length; i++) {
// Within the loop you can access each field of each object
// as shown below
// data[i].tier
// data[i].leagueName
// data[i].queueType
// data[i].playerOrTeamId
// data[i].leaguePoints
// data[i].wins
// data[i].losses
// data[i].rank
// data[i].veteran
// data[i].freshBlood
// data[i].hotStreak
// data[i].inactive
}
You can use methods like document.createElement("TAG_NAME") and document.appendChild(childElement) to insert the data into an HTML document.

In JavaScript console.log gives me every value from a for loop. However var.text only displays the last value. Why is this?

So I am using the Music Graph API to access and display artists similar to the current one (in this case "The Who.") However, when I use a for loop to go through the results, .text(artistNames) only prints the last name in the array (in this case it only prints Pink Floyd even though the array contains more artists.) However, console.log prints every name in the array. How to I get .text to print every name in the array?
Here's my code:
JavaScript
for (i = 0; i < response.data.length; i++) {
var artistNames = response.data[i].name;
$('#relatedArtists').text(artistNames);
console.log(artistNames);
}
HTML
<div id="relatedArtists">
</div>
You need to use append(), text() will clear the previous data
for (i = 0; i < response.data.length; i++) {
var artistNames = response.data[i].name;
$('#relatedArtists').append(artistNames);
console.log(artistNames);
}
or you can append with previous data with help of text() with callback
for (i = 0; i < response.data.length; i++) {
var artistNames = response.data[i].name;
$('#relatedArtists').text(function(i,text){ return text + artistNames; });
console.log(artistNames);
}
Because in each iteration you are overriding the previous value of the div.
Instead you can create an array with all the names then set that as the text of the div by joining the values like
var response = {
data: [{
name: 'n1'
}, {
name: 'n2'
}, {
name: 'n3'
}]
}
$('#relatedArtists').text(response.data.map(function(item) {
return item.name
}).join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="relatedArtists">
</div>

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

remove json attribute where attribute is a variable

I have a news feed where items in the feed are created from JSON returned from a server. When the user takes an action on an item, I want to remove it from the object via javascript.
The feed looks like this:
{"newsFeed":[{"feedId":"1",
"title":"item1 title",
"desc":"description of the item"},
{"feedId":"2",
"title":"item2 title",
"desc":"description of the item"}]}
I'm trying to remove a JSON attribute or entry where the feedId is passed in via a variable using jQuery. I'm not sure exactly where I'm going wrong here, but when I alert the feed before and after the removal of the object, I'm getting the same response:
function removeFromFeed(feedId){
var newsFeed=jQuery('div#newsFeed').data('newsFeed');
alert(newsFeed.toSource());
delete newsFeed.feedId[feedId]
jQuery('div#newsFeed').data('newsFeed',newsFeed);
alert(newsFeed.toSource());
}
If I undertand you correctly you want to remove e.g. this whole entry {"feedId":"1", "title":"item1 title", "desc":"description of the item"} if removeFromFeed(1) is called.
So what we need to do is remove an entry from an array.
New version which should work now. (btw. what is this toSource() my browser doesn't know this method)
//http://ejohn.org/blog/javascript-array-remove/
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
function removeFromFeed(feedId){
var data = jQuery('div#newsFeed').data('newsFeed');
var len = data.newsFeed.length;
for (var i = 0; i < len; i++) {
if (data.newsFeed[i].feedId == feedId) {
data.newsFeed.remove(i);
break;
}
}
jQuery('div#newsFeed').data('newsFeed', data);
}
Demo: http://jsbin.com/ekali3 (Code view: http://jsbin.com/ekali3/edit)
I'm not sure why the 'Array.prototype.remove' stuff was breaking my page, but I created a new array and just left out the object I wanted to remove.
var newsFeed=jQuery('div#newsFeed').data('newsFeed');
var newFeed={"feed":[]};
alert(newsFeed.toSource());
for (var i = 0; i < newsFeed.length; i++) {
if(newsFeed.feed[f].shiftId!=shiftId){
newFeed.feed.push(newsFeed.feed[f]);
}
}
seems to work.

Categories

Resources