Javascript - Read JSON by dynamic url inside loop - javascript

I have to make a call to a json that varies according to the id that I pass in the url, for this I must go through an array of identifiers and modify the url of the json inside the loop. But unfortunately it doesn't go inside the json function until the loop iterations have finished.
var IdList = ['1401', '5724', '5802', '3502', '2101'];
for(l = 0; l < IdList.length; l++){
$.getJSON('https://www.urljson.com?id='+IdList[l]+'', function(emp) {
price = emp.data.price;
currency = emp.data.currency;
});
}
Could someone tell me what is happening?
Thanks!

Related

Updating the value of an object inside a loop using javascript

I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.

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.

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

Breaking up large JSON object

I have a lot of files that I need to upload to my database, I am doing this through the browser and the server is having sizing issues with the data that is being sent to it and it rejects it. The server is not under my control in this context so I need to break up this object(s) into smaller objects before sending them to the server to get inserted into the database (rethinkdb if it matters). There is no order they need to be inserted in I just need to break up the file into smaller pieces.
I know I need a loop, but I do not understand how I can loop through 100 objects, save them as another object send them to the server, then start from 101 and so on....
Looping through all objects I get but this I cannot figure out or find examples for.
The code below is working for its purpose however it only goes to 250 then stops, it doesn't go past that.....
var lineData = jsonData.theData;
var newData = [];
var newLine;
//Shows on the browser console how many objects there are in the data
console.log(jsonData.theData.length);
//Goes through the Data and grabs the first 1000 lines
for(var i = 0; i< 250; i++){
newLine = lineData[i]
newData.push(newLine);
console.log(lineData[i]);
}
All you need to do is loop through your objects and for every 100th object, push out your new array and start over. So something like:
var lineData = jsonData.theData;
var newData = [];
for (var i=0; i < lineData.length; i++) {
newLine = lineData[i];
newData.push(newLine);
if (i && !(i % 100)) {
// upload newData
newData = [];
}
}
// check if there's any data left
if (newData.length) {
// upload the remaining data
}

How to store a Facebook Graph API response as a Javascript Array?

I'm wondering how to store the response from a Facebook API call into a Javascript array.
This is the call I'm making:
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
var grabbedarray = response.data[i].user.id;
console.log(grabbedarray);
}
})
The call FB.api('/MYAPPID/scores/?fields=user' returns a data set that has "name" and "id" properties for each element in the array, but I'm only interested in storing the "id" parts of the array.
The above code iterates through the response from the call, it checks user.id in each row of the array, and then the console.log shows the id for that row. This means that var grabbedarray is appearing several times in the console, showing a different id each time. I understand why this is happening, but I'm trying to get all the ids stored into one array, and then I'd like to console.log that.
So the final result in the console should be something like:
[456345624, 256456345, 253456435727, 376573835, 2652453245]
I've tried changing the call to FB.api('/MYAPPID/scores/?fields=user.id' in the hope that the response will show only a list of ids, but it's not working.
Does anyone have any idea how to solve this problem?
Thank you in advance!
To keep the approach you were using, you can push each new id you find into an array you define outside of the for loop.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
idArray.push(response.data[i].user.id);
}
console.log(idArray);
})
You could also use map to transform the response array into what you want.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
idArray = response.data.map(function(x){ return x.user.id });
console.log(idArray);
})

Categories

Resources