cant save all the locations values into my array - javascript

I am requesting to twitter to get all the locations of my users but then when i try to put them into my array all my objects get the same location(the last location of $.each).
its like i cant to loop through all the array values because of the each.function.i also tried putting outside the each.loop but same thing happens. Can someone tell me how to solve this.thanks!
function lookup_locations(user_ids){
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id="+user_ids+"&callback=?",
function(data){
$.each(data, function(i, item){
var location=item.location; console.log(location);
for(var i = 0; i < array.length;i++) {
array[i].location = location;
}
});
console.log(array);
});//get.json
}//lookup function

Try removing the for loop; i is being incremented by the $.each so you don't need it.
var array = [];
$.each(data, function(i, item) {
var location = item.location;
array[i].location = location;
});

Related

Split string then merge and remove duplicate value in array

I have an API and retrieve the data using jQuery.JSON. I use split to split the locations by "|". And now I'm trying to merge arrays that I've split using each in jQuery and remove the duplicates. I already tried concat. Is there a array_merge then array_filter function for javascript/jquery?
Here is my sample code below.
jQuery(document).ready(function($) {
let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
$.getJSON(get_json, function(data) {
let dept_arr = new Array();
let arr = new Array();
let i = 0;
$.each(data.departments, function(key, value) {
if (value.jobs.length > 0) {
$.each(value.jobs, function(key, value) {
dept_arr[i] = (value.location.name.split('|'));
i++;
});
}
});
console.log(dept_arr);
});
});
You need to loop over all the elements in the array returned by split(). And the easiest way to get rid of duplicates is with a Set.
jQuery(document).ready(function($) {
let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
$.getJSON(get_json, function(data) {
let dept_set = new Set();
$.each(data.departments, function(key, dept) {
$.each(dept.jobs, function(key, job) {
let locations = job.location.name.split('|');
$.each(locations, (i, loc) => dept_set.add(loc));
});
});
let dept_arr = [...dept_set]; // convert set to array
console.log(dept_arr);
});
});

getJSON getting all items but has undefined error

I'm using getJSON for my JSON data items, like this:
$.getJSON(projects, function (json) {
var firstThree = json.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 3);
var related = firstThree;
var i = '';
$.each(json, function(i) {
var sizeClass = JSON.stringify(related[i].pname);
console.log('sifzdfze'+sizeClass);
});
I checked on console, getting sizeClass item, it works. But but it also shows an error:
related[i] is undefined
What's the problem? Thanks!
As per your code you are accessing related as an array. So you are supposed to iterate over the items in the array. In your case related[i] is undefined because you are trying to access an item that is out of bounds of the particular array.
$.each(json, function(i) {
supposed to be
$.each(related, function(val, i) {
Also the above line, creates an i that is scoped to the each callback. So there is not need to declare it in the line above.
Here val is the current value in iteration whose index is i. It can be simplified as
$.each(related, function(val, i) {
var sizeClass = JSON.stringify(val.pname);

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined
You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}
Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.
This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.
Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

FInd object in array by value and update entire object

I have a list of objects and sometimes I receive an update from the API for one of those objects and what I need to do is to find the object with the id of the one to update and update the entire object...
I was trying to avoid a for loop because the list could be very very long.
So what I was trying to use is $.grep but it doesn't seem to work as expected.
Here is what I tried so far:
// item is the response data from the API
var item = res.item;
var index = $.grep(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
arrayOfItems[index] = item;
the item is not updated unfortunately...
If it's speed you're after, especially with a long list, you may consider indexing your list by id when you first retrieve it, making updates later quicker than having to loop the entire array to find an index.
To demonstrate, assume you have retrieved an array of objects
var data = [
{id:1,data:'hello'},
{id:2,data:'world'},
{id:3,data:'foo'},
{id:4,data:'bar'}];
now create an object which represents your data where the property is the Id (object properties cannot start with a number, so if id is numeric, prefix it) and the value is the index back into the original array. So, the above data would be transformed to
var dataIndex = {
id1:0,
id2:1,
id3:2,
id4:3
};
This can be done trivially with a function
function indexDataById(data)
{
var index = {};
$.each(data, function(e,i){
index['id' + e.id] = i;
});
return index;
}
var dataIndex = indexDataById(data);
Now, when it comes to your update, you can find the index instantly using the id
var updateId = 2;
var elementIdx = dataIndex ['id' + updateId];
data[elementIdx] = myNewData;
The one complication is that you need to go back and update the index if the id of the new data has changed:
var updateId = 2;
var elementIdx = dataIndex [`id` + updateId];
data[elementIdx] = myNewData;
delete dataIndex[elementIdx]
dataIndex['id' + myNewData.id] = elementIdx;
This should be easy enough to handle atomically with your update.
$.map and $.grep return both an array so you will never get the index.
Inside $.map or $.grep function you need to return true or false based
on your filter logic. They re not useful in your case.
if your structure is not ordered you can only loop trough it and stop the loop when you find your element... like that:
var item = res.item;
var index = "";
$.each(arrayOfItems, function(i,v){
if(item.id == v.id){
index = i;
return true;
}
});
arrayOfItems[index] = item;
if you wanna order your structure before loop use this:
arrayOfItems.sort(function(a, b) {
return a.id > b.id;
});
i ve made a fiddle with an example https://jsfiddle.net/L08rk0u3/
try this way using $.grep
var arrList = [
{name :11,id :11},{name :12,id :12},{name :111,id :111},
{name :13,id :13},{name :15,id :15},{name :11,id :11},
{name :41,id :41},{name :31,id :31},{name :81,id :81},
{name :91,id :91},{name :13,id :13},{name :17,id :17},
{name :1111,id :1111}
]
console.log(arrList);
var respItem ={name :1111000,id:1111};
var intSearchedIndex;
$.grep(arrList,function(oneItem,index){
if(respItem.id==oneItem.id){
return intSearchedIndex = index;
}
})
arrList[intSearchedIndex] =respItem;
console.log(intSearchedIndex,arrList);
Try with map method like this.
Code snippets:
// item is the response data from the API
var item = res.item;
var index = $.map(arrayOfItems, function (e, i) {
if (e.id === item.id) {
return i;
}
});
if(index.length)
arrayOfItems[index[0]] = item;
Update:
arrayOfItems[index] = item;
This will work if index array has an single element. See fiddle
But,
arrayOfItems[index[0]] = item;
This is the appropriate way since it is an array.

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!

Categories

Resources