i value not iterating in Callback functions [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
This may be a question without any R&D but I am on a busy schedule and very new to these callback functions, The problem is I am getting a json payload from a webapp and I am trying to parse it , so this payload has a array of objects , but when i use this in my script i am getting only the last array index value.
below is the code and attached console output for reference , please suggest where i am going wrong
var case1 = payload.Case;
var i=0;
for(i=0;i<case1.length;i++)
{
var c1 = case1[i];
c1.retrieveAttributes(function(){
console.log(i+ " i");
console.dir(c1.attributes);
});
}
The i value in console is always 6.

You're having an issue with 'closure' scope. Try passing 'i' into your function like this.
var case1 = payload.Case;
var i=0;
for(i=0;i<case1.length;i++)
{
var c1 = case1[i];
c1.retrieveAttributes(function(i){
console.log(i+ " i");
console.dir(c1.attributes);
});
}
That should preserve the true value of 'i'.

Related

I want toarray in JavaScript? Where is it my fault? [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
Closed 4 years ago.
I add This code to my page and I want to complete city when user tap a zipcode
and my alert dosen't show
var obj = {
"01400": "ABERGEMENT-CLÉMENCIAT",
"01640": "ABERGEMENT-DE-VAREY",
"01500": "AMBÉRIEU-EN-BUGEY",
"01330": "AMBÉRIEUX-EN-DOMBES",
"01300": "AMBLÉON",
"01500": "AMBRONAY",
"01500": "AMBUTRIX",
"01300": "ANDERT-ET-CONDON",
"01350": "ANGLEFORT",
"01100": "APREMONT",
"01110": "ARANC",
"01230": "ARANDAS",
"01100": "ARBENT",
"01300": "ARBIGNIEU",
"01190": "ARBIGNY"
};
var myVariable = obj .01400;
alert(myVariable);
Firstly, there is no key named 97433 in your object
Secondly, even if there was you cannot use property accesors with object keys which begin with a number. You need to use bracket notation.
Lastly, use console.log() for debugging as alert() coerces types and blocks the UI logic.
var myVariable = obj['97433'];
console.log(myVariable);

jQuery-UI Dialog only showing last iteration of the for loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 years ago.
Don't know if I'm being blind but every time I look at this code the logic makes sense. I am trying to iterate through this for loop and for each iteration generate a dialog box with the ID of #dialog-(i) but it only show's the last iteration of 200. The code is below:
var i;
for(i=1;i<200;i++){
$("#dialog-" + i).hide();
$('#meetings_box-' + i).click(function() {
var dialog = $("#dialog-" + i).dialog();
if (dialog) {
console.log('yay');
console.log(dialog);
} else {
console.log('nay');
}
});
};
Any help to finding the issue, probably something really dumb
This is because click will happen sometime in the future and by then the loop has already finished it's execution and the value of i is updated to the last value. Instead of var you can use let

Issue getting my objects properties [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 4 years ago.
Hi guys I have just started learning to code and I have hit a road block in accessing the properties of the object I have created.
Here is my object.
var restaurantOrder = {
"my entree": "cheeseburger",
"my side": "fries",
"the drink": "water"
};
I would like to get the value of entree however nothing I am trying seems to work :(
Here is what I have tried.
var entreeValue = restaurantOrder.my entree;
var entreeValue = restaurantOrder[my entree];
var entreeValue = restaurantOrder.[my entree];
var entreeValue = restaurantOrder.["my entree"];
None of the above lines work :( Thank you for your help.
Because the properties of your restaurantOrder object have spaces, you will need to use [] to access them. You cannot use . like you can with a property name that is a single word.
Also, because of the spaces you will need to enclose the property name with quotes, so either:
var entreeValue = restaurantOrder["my entree"];
or
var entreeValue = restaurantOrder['my entree'];
will work.

How to dynamically name arrays in javascript? [duplicate]

This question already has answers here:
dynamic array names javascript
(7 answers)
Closed 7 years ago.
I haven't found an answer to this question on the site. How would I dynamically name arrays in javascript? I need to generate a number of arrays, the number of which is determined at run time. I am trying to make separate ajax requests that sends individual arrays to a php script for processing.
I have come up with this but it does not work:
var 'objectArray'+id = [];
The typical way would be to have an array of arrays.
var arrayOfArrays = [];
arrayOfArrays[id] = []; // add sub array
What you're asking for is a form of dynamic scoping and JavaScript does not support it. You can call the compiler and eval it but that's a pretty bad idea.
Easiest thing is just creating an object and setting them in it
var objectArrays = {};
objectArrays[id] = [];
The way to do literally what you want is finding the scope you're currently in and setting it in it or using eval.
A good way is to use an array of arrays as suggested:
var objectArray = [];
objectArray[id] = [];
If you do not want to use your own array, you can use window object which holds the window global vars in order to store it there as a value as a global var (not a good practice though):
window["objectArray" + id] = [];
Finally, a (bad in this case) alternative way of doing it is by using eval (which is a way to evaluate an expression at runtine in JavaScript in a sense):
eval("var objectArray" + id + " = [];");

Get key from JSON object [duplicate]

This question already has answers here:
Javascript get object key name
(8 answers)
Closed 5 years ago.
I'm using the flat-cache NPM package and I'm currently blocked because I can't recover the key from the data I'm caching. It must be very simple, but I'm starting with the JS and I'm pulling my hair out on this problem.
Simple example of code :
main.js
var flatCache = require('flat-cache')
flatCache.setKey('d86f003c-bf0a-4b08-9744-1081c78ece9d', {"creation":"2018/02/20", "link":"https://www.npmjs.com/package/uuid","comment":"UUID", "tags":["NPM", "UUID"]});
var a = flatCache.all();
console.log(a);
Example of data from console :
{
"d86f003c-bf0a-4b08-9744-1081c78ece9d": {
"date":"20180220",
"comment":"Hello world",
"tags":[
"hello",
"worlds"
]
}
}
What would be the procedure to follow to retrieve the key : d86f003c-bf0a-4b08-9744-1081c78ece9d ?
Thank you in advance for your answer !
Use Object.keys method.
In your case:
// `a` is defined somewhere there
...
Object.keys(a); // an array of object keys - but only the first level
console.log(Object.keys(a)[0]); // should log `d86f003c-bf0a-4b08-9744-1081c78ece9d`
for further reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Categories

Resources