Javascript: JSON key values not updating on request - javascript

I'd like to update my JSON value based on selection.
So for that I have simply update my json value as data.childShow = true.
Now as per the screenshot on line no 78 it's actual value is false and after updating it's value to true ( ref line no 84 ) and it shows as value updated on line no 85 but when i expand that console object it shows as false.
So, why the values are differing when open the object on console log ?
Screenshot while not opening object of line no 85
P.S: Before raising this question I have already tried this demo, but it is not working in my actual application so that i raised this question.

Try this thing in console it might solve your confusion. Add an object like let data = { childShow: false }. Then log it in console. Do not expand right now. Now change the value of data.x = true; in expanded value but it also has childShow=false in first line. Now expand console log value. You can see it is displaying childShow = true. So it might be fetching current values when we expand.
You can also log childShow and check what exactly values hold by data.childShow. Like in below snippet. It will show you when you do console.log(data.childShow); first time it will show false and second time it will show true which is as expected.
Try with below like. 1. Open console of browser. 2. Click on Run Code Snippet. 3. Expand object in console.
const data = {
childShow: false,
}
console.log(data);
console.log(data.childShow); // Output false
data.childShow = true;
console.log(data);
console.log(data.childShow); // Output true

Related

Array shows empty, but should have one element

Okay guys so I've run into a problem on some code I've been working on. In the code below, I'm trying to console log the length of an array, but after printing to the console, I get an output of 0 for the array's length, and when I print the array itself, it shows that it is empty, but I can click the drop down arrow and see the element inside it.
// randomly selects card from array
export const selectCard = arr => {
const randomArr = Math.floor(Math.random() * arr.length);
console.log(arr.length);
console.log(arr);
}
Image of logged array length and empty array with an element inside.
To test what was happening, I decided to console log the array in a different function that is in the same file where the array is created. The array (blackCards) is stored in an object.
let packArr = {
data: {},
packToUse: [],
whiteCards: [],
blackCards: [],
};
Console logging the array (blackCards) in another function logs this:
const seperatePacks = (data) => {
// add white cards to array
packArr.whiteCards.push(data.whiteCards);
// add black cards to array
packArr.blackCards.push(data.blackCards);
// console log blackCards array
console.log(packArr.blackCards);
};
Image of logged array from a different function which is within the same file where the array is created and stored.
Here's a little more about how my code works. When a user clicks on a button, an event listener is activated, which calls other functions that eventually get json from a sever, then I add that data to the array, which you see in the code above. So now that you know how the code works, I can get to what is causing me to be even more confused. So, on the first click, I get the outcome of all the previous code and images combined, but if i click on the same button again, or click on a different one, I get the desired outcome (if I click on two button I get two elements in the array, so it's working correct). So, two or more clicks and the program works the way it should. Any help here would be great. Also sorry if this post was a little scuffed, it is my first one.
Here are the functions that eventually call selectCard
elements.packs.addEventListener("click", (e) => {
const packID = e.target.closest(".pack").id;
if (packID) {
packsToUse(packID);
// create black cards
blackCardDisplay(packArr.blackCards);
}
});
Above is the listener that was mentioned earlier, which calls the function below, that will call selectCard.
export const blackCardDisplay = data => {
const card = `
<div class="cards card--black">
<h1 class="card--black-text card--text">${selectCard(data)}</h1>
</div>
`;
}
Here is the output after pressing two buttons. The array should contain two elements but in this case it only shows one. However when I expand the array, it shows a length of two instead of just one.
Console image of two button clicks
EDIT: After reading some of the comments I realized I forgot to mention that the contents of blackCards is an array. So I have an array within an array.
So, after reading some comments I decided to implement #charlietfl's comment that maybe the array was console logged before the ajax call had been completed. Although this did not explicitly fix the problem, it set me on the right track to the solution.
Here is how I solved this problem:
I took the comments given about the console log completing before the ajax call could finish, and from there, I did some research and found this very simple article:
https://www.programmersought.com/article/26802083505/
In this article was an example using the setTimeout() method.
Here is the final solution to my problem.
export const selectCard = arr => {
const randomArr = Math.floor(Math.random() * arr.length);
setTimeout(() => {
console.log(arr.length);
console.log(arr)
}, 1000);
}
Here is the output after adding the setTimeout() method on the first button press.
Image of solved array length and array console log
I'm not aware if this is the best solution for the problem, because I've seen some people disapprove of using this method in the past, but it will work fine for what I'm doing at this point. If anyone has a better way of solving this I would love to hear it!

Printing object gives different value than printing a property of that object

I've got a strange situation in my typescript file where these two console.info calls show separate values for overage:
this.rows[index].overage = 17;
console.info(this.rows[index].overage);
console.info(this.rows[index]);
The first printout shows the expected value of 17. The second, where the whole object is displayed, show the old value of 90 for overage. How is that possible?
Rows is defined like so:
rows: UsageDisplayData[];
export interface UsageDisplayData {
id: number;
overage: number;
// A bunch of other properties
}
It's hard to say without an MVCE exactly what is happening, but the expanded view in the dev console is usually a "live" view and thus will show whatever the latest value is. Example:
let obj = { m: 17 };
console.info(obj.m);
console.info(obj);
obj.m = 90;

Angular.js model not updateing after first time

I have an example here:
http://www.search-this.com/examples/angular-help/
If you double-click "Text Message" in the list it brings up an input box.
type "one" in the input box and click the update button.
Notice the console.log
click SmsResponseActionParmAndValue to expand and locate the "Text Message" option
click ParmAndValue to expand and notice the Value property has our "one" value we typed in.
Now type two in the input box and look at the console.log and notice it doesn't update? It only updates the first time?
Help please...
which is getting updated in selected object not in main JSON object.
$scope.updateDetails = function () {
console.log("update");
console.log($scope.actions); //
console.log($scope.selectedAction); // look in this object updated you have to override it to original object or use 2 times ng-repeat to bind.
};
This is very ugly i know but its a solution:
$scope.updateDetails = function() {
angular.forEach($scope.actions.SmsResponseActionParmAndValue,function(action){
if(action.Description === $scope.selectedAction.Description){
console.log($scope.selectedAction)
action.ParmAndValue = $scope.selectedAction.ParmAndValue
return;
}
});
console.log($scope.actions)
};
The problem is that the updated model doesn't point to the same array in memory as the original object so we have to update the array that the original object points to.

JSON.parse(json_string_from_php) produces weird array

I'm having a bit of difficulty with transferring a JSON object from the server to the client-side javascript
I have a rows of data fetched from MySQL query stored into $result
Here's the code:
var json = '<?= json_encode($result->fetch_all()) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //index.php:23
console.log(json); //index.php:24
This is the result in chrome console:
Can someone tell me:
1. Why line 23 shows length of 5 when folded, then only show length of 4 when unfolded?
2. Where did word5 go? FYI, the word that disappears changes every time I refresh.
I am able to reproduce your screenshot.
I purposely hovered over the little "i" to reveal its tooltip. It states "Object state below is captured upon first expansion.
This means that if you print the array, don't expand it, modify the array (say with a pop()) then when you expand it you will see the modified array.
Demo: JSBin
console.log logs your state of the object to the console when it is hitting the console.log while inspecting the array (or any object) shows you the current state of it.
var a = [1,2,3,4,5].map(function(){ return new String(); });
console.log(a);
a.pop();

Angularjs grid selectedItems always returning undefined?

Any reason the angularjs grid in my sample won't show the selectedItems properly? That is, any time I try to reference the selectedItems I get "undefined." I've tried in Chrome and IE with the same result.
I've made a plnkr that is the "basic" example on the angular grid page with a bit of extra javascript to try and show the selected items.
The plnkr: http://plnkr.co/edit/wPnMGQOzKSOTdeaAjoB8?p=preview
The relevent code:
$scope.gridOptions = {
data: 'myData',
selectedItems: $scope.mySelections,
afterSelectionChange: function (row, event) {
if (row.selected) {
alert('Items selected ' + $scope.mySelections);
alert('Items selected ' + $scope.gridOptions.selectedItems)
}
}
};
I get "undefined" when trying to evaluate the selected items, either with $scope.mySelections or via the grid directly. I've put a "debugger;" line in "if" and checked the values - there doesn't appear to be a selectedItems property on the grid?
(edit: removed the ** from the code block. Forgot you can't boldface code here)
You forgot to initialize your $scope.mySelections property. Because of this, every time you'd print its value, you would get undefined.
Check a fixed plnkr.
Of course, it alerts a [Object object] for each, but this is a matter of how you want to print your objects.
If you want to alert your objects in a more sensible way, you could do something like this plnkr.

Categories