Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create an json structure with data which will get from an api call. I can generate the structure by using following code. But how can I restructure the code to remove nested call of function and loops.
var temp = {
applications: []
};
api.getApplications(conceptId)
.then((applications) => {
for (var i = 0; i < applications.length; i++) {
(function(indexOfAppArr) {
let applicationId = applications[indexOfAppArr].id;
temp.applications.push({
id: applicationId,
databases: []
});
api.getDbs(conceptId, applicationId)
.then(databases => {
for (var j = 0; j < databases.length; j++) {
(function(indexOfDatabasArr) {
let databaseid = databases[indexOfDatabasArr].id;
temp.applications[indexOfAppArr].databases.push({
id: databaseid,
tabels: []
});
api.
getSchema(conceptId,
applicationId, databaseid).
then(function(schemas) {
for (var k = 0; k < schemas.length; k++) {
(function(indexofschemaarr) {
let schemaid = schemas[indexofschemaarr].id;
api.getTable(conceptId, schemaid)
.then(function(tables) {
console.log(tables);
})
})(k)
}
})
})(j)
}
})
})(i)
}
})
Here is the JSON structure which i want to create.
{
applications:[{
id:'',
databases:[{
id:'',
tabels:[
{
id:'',
columnId:''
}
]
}]
}]
};
If you read a little you'll actually learn how to do it. I personally haven't had the need to learn it yet but it sounded interesting, here is an excellent website that I found for you:
https://javascript.info/promise-chaining
it explains there how to "restructure" the code you are asking by putting it in less words:
loadScript("/article/promise-chaining/one.js").then(function(script1) {
loadScript("/article/promise-chaining/two.js").then(function(script2) {
loadScript("/article/promise-chaining/three.js").then(function(script3) {
// this function has access to variables script1, script2 and script3
one();
two();
three();
});
});
});
I'm sure it only takes less than 30 mts of reading. Best of luck!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Hello I'm new to JS and fetch api. I'm facing a problem that the following code perfectly works and show the datas from that api when I run that code with node and display in on the console. But when I try to show the datas from the api to the browser with JS DOM , it shows 403 error even though I include the authentication in the headers.
fetch('https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/arrow'
, {
method: 'GET',
mode: 'no-cors',
headers: { app_id: "api_id", app_key: "api_key" },
})
.then((response) => response.json())
.then((data) => {
let noun = document.querySelector("#forNoun")
let verb = document.querySelector("#forVerb")
let nounEg = document.querySelector("#nounEg")
let verbEg = document.querySelector('#verbEg')
let searchbtn = document.getElementById("search")
let searchWord = document.getElementById("word")
let nounDef = document.createElement("p");
let verbDef = document.createElement("p")
let lexicalEntries = data.results[0].lexicalEntries;
let length = lexicalEntries.length
for (let i = 0; i < length; i++) {
console.log(lexicalEntries[i].lexicalCategory.text);
nounVerb.innerHTML = lexicalEntries[i].lexicalCategory.text
let senses = lexicalEntries[i].entries[0].senses;
for (let x = 0; x < senses.length; x++) {
if ("examples" && 'synonyms' in senses[x]) {
// console.log(senses[x].definitions[0])
noun.append(senses[x].definitions[0])
}
else if ('examples' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else if ('synonyms' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
}
}
});
`
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Does anyone have any idea why i is not defined in this loop? i cannot figure it out...
I'm trying to paginate through the pages of data received from an api and gather it all into one array and store it in state, but my for loop doesn't seem to be working because of the error: "i is not defined"
how else should i go about this???
gatherAllCharacters = () => {
fetch(`https://rickandmortyapi.com/api/character/`)
.then(res => res.json())
.then(data => {
let characters = data.results;
const totalPages = data.info.pages;
if (totalPages > 1) {
for (i = 2; i <= totalPages; i++) {
let page = i;
fetch(`https://rickandmortyapi.com/api/character/?page=${i}`)
.then(res => res.json())
.then(data => {
characters = characters.concat(data.results);
if (page === totalPages) {
this.setState({ allCharacters: characters });
}
});
}
} else {
console.log("none");
}
});
};
You can create a for loop like you have done above
for (i = 2; i <= totalPages; i++) {
//perform loop
}
However this generates a variable i in the global namespace and this is generally speaking a bad idea.
therefore you should initialise i before using it like so:
for (let i = 2; i <= totalPages; i++) {
//perform loop
}
Therefore ECMA decided to have a mode where this (and my other features that would cause undesirable side effects would instead throw an error).
see more here https://www.w3schools.com/js/js_strict.asp
As your app is in use-strict mode it will be throwing the error "i is not defined"
Remember to initialize any variable before using it!
Couple things you should know about let and var
var and let can change their value and const cannot change its value
var can be accessible anywhere in function but let and const can only be accessible inside the block where they are declared.
Because i is not defined. You need a var or let in front of i to define a new variable.
for(let i = 2; i <= totalPages; i++ )
- for (i = 2; i <= totalPages; i++) {
+ for (let i = 2; i <= totalPages; i++) {
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I know I can't save data to file with javascript, but is there any solution to create configuration file (JSON) on local file system where I can write data, make some changes like add or remove object and save this. I don't want lose my new data when i next time starts my app. Any ideas?
Thanks for help.
UPDATE
I want to use it on different computers.
You could write yourself a SettingsService to read and write the data via the localstorage:
class SettingsEntry {
constructor(public key: string, public value: any) { }
}
export class SettingsService {
private SETTINGS_KEY = "__SETTINGS__";
private _settings: Array<SettingsEntry>;
constructor() {
let settings = localStorage.getItem(this.SETTINGS_KEY);
if (settings && settings != undefined) {
this._settings = JSON.parse(settings);
}
else {
this._settings = [];
this.save();
}
}
private indexOf(key: string): number {
for (let i = 0; i < this._settings.length; i++) {
if (this._settings[i].key == key) {
return i;
}
}
return -1;
}
private save() {
localStorage.setItem(this.SETTINGS_KEY, JSON.stringify(this._settings));
}
get(key: string) {
let index: number = this.indexOf(key);
if (index >= 0) {
return this._settings[index].value;
}
return null;
}
set(key: string, value: any) {
let index: number = this.indexOf(key);
if (index >= 0) {
this._settings[index].value = value;
}
else {
this._settings.push(new SettingsEntry(key, value));
}
this.save();
}
}
Use it like this in your components or services:
_settingsService.set("time", new Date());
let time = _settingsService.get("time");
Working Plunker for example usage
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
<script>
$.getJSON('url/rest/1', function (data) {
var mydata = JSON.stringify(data);
});
</script>
This is my code. For console.log(mydata) my output is :
{
"data":[
{
"orderid":"9",
"ordercode":"TTG-13-06-3"
},
{
"orderid":"12",
"ordercode":"TTG-13-06-4"
},
{
"orderid":"15",
"ordercode":"TTG-13-06-5"
},
{
"orderid":"20",
"ordercode":"TTG-13-06-6"
},
{
"orderid":"24",
"ordercode":"TTG-13-06-7"
},
{
"orderid":"26",
"ordercode":"TTG-13-06-8"
},
{
"orderid":"31",
"ordercode":"TTG-13-06-9"
},
{
"orderid":"36",
"ordercode":"TTG-13-06-10"
},
{
"orderid":"41",
"ordercode":"TTG-13-06-11"
},
{
"orderid":"44",
"ordercode":"TTG-13-06-12"
}
],
"status":"success"
}
I need to get ordercode alone in console. How can I achive it?
Use $.map to transform each object in your collection:
var orderCodes = $.map(data.data, function(entry){
return entry.ordercode;
});
and get an array of all ordercodes.
See: http://api.jquery.com/jquery.map/
If you're using any sort of functional programming library (i.e. underscore) this operation is usually abstracted into a method called pluck: http://underscorejs.org/#pluck
Use each of jQuery
$.each(data.data,function(index,value){
console.log(value.overcode)
})
The return data is array of objects, thus we need to loop through it to retrieve ordercode property.
var mydata = JSON.stringify(data);
// Check if mydata object has "data" property before looping
if(mydata.hasOwnProperty(data)) {
for(var i = 0; i < mydata.data.length; i++) {
console.log(mydata.data[i].ordercode);
}
}
$.each(myData.data, function (i, obj) {
console.log(obj.ordercode);
});
Second using foreach-
var parsedMyData = JSON.parse(mydata);
var arr = [];
for(i in parsedMyData) {
arr.push(parsedMyData[i].ordercode);
}
console.log(arr);
o/p- ["TTG-13-06-3", "TTG-13-06-4", "TTG-13-06-5".....]
Best and shortest option-
var data=JSON.stringify(mydata);
$.map(data, function(value){
console.log(value.ordercode);
});
First option -
var parsedMyData = JSON.parse(mydata);
var objectForConsole = $.extend({}, $.map(parsedMyData, function(val) {return val.ordercode; }));
console.log(objectForConsole);
This will print: Object {0: "TTG-13-06-3", 1: "TTG-13-06-4"....}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
Here is my code
for (var i=0; i<5; i++) {
var url = generate_url(i) ;
$http.get(url).then(function(response){
var param2 = response.data.param2
$scope.outputData.push({'index':i, 'param':param2}) ;
}) ;
}
In this example, I suppose to obtain an array in the $scope.outputData with data similar to this:
[
{'index':0,param:'a'},
{'index':1,param:'b'},
{'index':2,param:'c'},
{'index':3,param:'d'},
{'index':4,param:'e'},
]
but what i get is data like this:
[
{'index':4,param:'a'},
{'index':4,param:'b'},
{'index':4,param:'c'},
{'index':4,param:'d'},
{'index':4,param:'e'},
]
In this case, the externel data that I mean is the variable i,
Please could you tell me the trouble ? and how do I proceed to attend my goal? Thank you in advance and sorry for my english :)
You can create a closure over the i variable to make sure it still has the value you want it to have when you use it.
for (var i=0; i<5; i++) {
(function(counter) {
var url = generate_url(i);
$http.get(url).then(function(response){
var param2 = response.data.param2
$scope.outputData.push({'index':counter, 'param':param2}) ;
});
}(i));
}
But if the ordering of the resulting array matters, you will have to create a temporary array and then sort it on index.
You can use $q.all if you don't want to process any of the requests untill they have alle completed.
Something like this:
var promises = {};
for (var i=0; i<5; i++) {
var url = generate_url(i) ;
promises[i] = $http.get(url);
}
$q.all(promises).then(function(result) {
for (index in result) {
var param2 = result[index].data.param2
$scope.outputData.push({'index':index, 'param':param2}) ;
}
});
That should also preserve the ordering.
The docs for $q are here.
This is a closure issue, the correct way to do it would be
for (var i=0; i<5; i++) {
getData(i);
}
var getData=function(index) {
var url = generate_url(index) ;
$http.get(url).then(function(response){
var param2 = response.data.param2
$scope.outputData.push({'index':index, 'param':param2}) ;
}) ;
}