How to get length of array inside of objects in javascript? [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 11 months ago.
Try to get length of array inside an object
image above is return of Res
I want to check if every tenor length is equal or more than zero.
But, I stuck in how to call itemCounter"i" when loop it
var tenorCount = Object.keys(res).length;
var flagTenor = false;
try{
for(var i=1;i<tenorCount;i++){
if (res.itemCounter_+i.tenor.length < 1){ //Stuck in here
flagTenor = true;
}
}
}catch(e){
console.log(e);
}
How to call itemCounter"i" correctly?

Try like this using template literals and computed property names
if (res[`itemCounter_${i+1}`].tenor.length < 1)
Example
const res = {
itemCounter_1: {
tenor: ["one"]
},
itemCounter_2: {
tenor: []
},
}
var tenorCount = Object.keys(res).length;
var flagTenor = false;
try {
for (var i = 0; i < tenorCount; i++) {
if (res[`itemCounter_${i+1}`].tenor.length < 1) {
flagTenor = true;
}
}
} catch (e) {
console.log(e);
}
console.log(flagTenor);

Related

Accessing global variable inside callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am facing an issue related to the variable scope. Initially set "successCount" and "failedCount" variables as '0' and incremented that value after each success/failure iteration. But after the iteration got the initial value only for those variables.
var successCount = 0;
var failedCount = 0;
var counter = 0;
var data = {};
for (var i = 0; i < 5; i++) {
updateField(data, (response) => {
if (response.status) {
successCount++;
} else {
failedCount++;
}
});
counter++;
}
Accessing variable outside the loop
if(counter === 5) {
console.log(successCount);// Value is still 0
console.log(failedCount);// Value is still 0
}
Any solution or what I am wrong with this code.
Thanks in advance
Since the variables are updated in the callback you need to make sure that your console.log is not called before your callback.
You can try to convert your update function into a promise to be able to run the console log after all the function are resolved.
var successCount = 0;
var failedCount = 0;
var counter = 0;
var data = {};
function asyncUpdateField(data) {
return new Promise((resolve) => {
updateField(data, (response) => {
if (response.status) {
successCount++;
} else {
failedCount++;
}
resolve();
});
});
}
const promisesUpdateField = [];
for (var i = 0; i < 5; i++) {
promisesUpdateField.push(asyncUpdateField(data));
}
Promise.all(promisesUpdateField).then(() => {
console.log(successCount);// Value is still 0
console.log(failedCount);// Value is still 0
});
As it seems, the function updateField may be asynchronous. That's why your console.log() is being called before the execution of that function and at which point, value of successCount and failedCount is 0.

Is there a more beautiful way to catch errors on a block of JSON Arrays? [duplicate]

This question already has answers here:
How to avoid 'cannot read property of undefined' errors?
(18 answers)
Closed 3 years ago.
I have a bunch of data in a JSON that I need to parse, but some of them does not exist.
Hence, I currently, have the following try/catch(e) but is there a more elegant way to do so?
for (var u = 0; u < 100; u++) {
try {
var reactions = JSON.parse(dataParsed.data[u].reactions.summary.total_count)
} catch (err) {
console.log(err)
var reactions = 0
}
try {
var comments = JSON.parse(dataParsed.data[u].comments.summary.total_count)
} catch (err) {
var comments = 0
}
try {
var shares = JSON.parse(dataParsed.data[u].shares.count);
} catch (err) {
var shares = 0
}
postArray.push({
"id": dataParsed.data[u].id,
"message": dataParsed.data[u].message,
"createdTime": dataParsed.data[u].created_time,
"fullPicture": dataParsed.data[u].full_picture,
"reactions": reactions,
"comments": comments,
"shares": shares
})
}
You can use && (short circuiting ) and || (default vlaue)
var reactions = dataParsed && dataParsed.data[u] && dataParsed.data[u].reactions && dataParsed.data[u].reactions.summary && dataParsed.data[u].reactions.summary.total_count || 0
There's a proposal for optional chaining and Nullish Coalescing
var reactions = dataParsed?.data[u]?.reactions?.summary?.total_count ?? 0
Make a function:
function safeParse(propStr) {
let r = 0;
try {
r = propStr.split(/\.|\[|\]/g).reduce((a, c) => a[c], {});
} catch(e) {}
return r;
}
var reactions = safeParse("dataParsed.data[u].reactions.summary.total_count");
var comments = safeParse("dataParsed.data[u].comments.summary.total_count");
var shares = safeParse("dataParsed.data[u].shares.count");
Just use value|0 to catch the value via binary operation. If value exists, then it will return value if not, then it will return 0

JS array length returns 0 [duplicate]

This question already has answers here:
Wait until all jQuery Ajax requests are done?
(22 answers)
array.length is zero, but the array has elements in it [duplicate]
(2 answers)
Call async/await functions in parallel
(12 answers)
Closed 4 years ago.
Using the following code I call a function ("firstFunction") that generates an Array and returns the array.
async function doProcess() {
const checkState = await firstFunction();
console.log(checkState);
console.log(checkState.length);
return checkState;
}
Using console.log(checkState); I am able to print the data from the whole Array to the console.
When I try to access the values or array data, for example, console.log(checkState.length);, I get 0. What am I doing wrong here?
Edit [added "firstFunction"]:
function firstFunction() {
var array = [];
var url3 = "/Home/CheckPrintService?printer=" + document.getElementById("printerName").value;
$.get(url3, null, function (data3) {
$("#msgPrinterName").html(data3);
var str = $("#msgPrinterName")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
//console.log($("#msgPrinterName")[0].innerText.toString());
});
var e = document.getElementById("ddlViewBy");
var deviceType = e.options[e.selectedIndex].text;
var url2 = "/Home/CheckIfValidIP?input=" + document.getElementById("ipAddress").value + "&type=" + deviceType;
$.get(url2, null, function (data2) {
$("#msgIPPort").html(data2);
var str = $("#msgIPPort")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
});
var url = "/Home/CheckPrinter?printer=" + document.getElementById("printerName").value;
$.get(url, null, function (data) {
$("#msgPrintService").html(data);
var str = $("#msgPrintService")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
});
return array;
}

Running functions using string name from array [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 5 years ago.
I have an array that has a bunch of function names. I am not storing the function in an object.
for (i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
This doesn't work, any ideas?
Thanks.
The code you posted works, so perhaps the code that defines the functions isn't quite right. Here is a fully working example.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
yep,
again
];
for (var i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
If you wanted to get a bit of design help in your code, you could introduce a factory. This has the added benefit of making unknown function names explicit.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
function functionFactory(name) {
switch (name) {
case 'yep':
return yep;
case 'again':
return again;
default:
throw `${name} not a known function in functionFactory`;
}
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var func = functionFactory(view_functions[i]);
func();
}
If you only have string names, I recommend not using string names... but you could go full-evil and use eval...
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var n = view_functions[i] + '()';
eval(n);
}
But why not store the actual functions in the array instead...

Having trouble detecting undefined objects in an array

Quick bit about my background:
-been learning for about 3 months;
-work in tech support for a small software company. 2 years exp.
-a lot of knowledge is secondhand and I am still learning the basics
I am trying to create an object every second. The object is created directly to the last position of an array that remembers a set quantity of objects created before the most recent one
function Fruit(name, position) {
this.name = name;
this.position = position;
}
var showXMostRecentFruits = 20;
var fruitCounter = 0;
function generateName() {
var name = 'Experimental Fruit' + fruitCounter;
return name;
}
var fruitsArray = [];
function shiftFruits() {
for (i = 0; i < showXMostRecentFruits; i++) {
fruitsArray[i] = fruitsArray[i + 1];
}
function updateFruitPositions() {
for (i = 0; i < showXMostRecentFruits; i++) {
fruitsArray[i].position = i;
}
}
var fruitTimer; //used for setting and clearing setTimeout
function createNewFruit() {
shiftFruits();
fruitsArray[showXMostRecentFruits - 1] = new Fruit(generateName());
updateFruitPositions();
fruitCounter += 1;
fruitTimer = setTimeout(function() {
createNewFruit();
}, 1000);
}
Say the function createNewFruit() is run once
createNewFruit();
Then I try to pull some meaning from the array
console.log(fruitsArray[19];
All I get is:
Fruit {}
undefined
This issue is when I want to run a loop (see updateFruitPositions()) that updates a propery of each object in the array, an error is returned that the objects are undefined. I get that they are undefined because they are not assigned to unique variables (at least not that I'm aware of). How can I identify the objects or how can I create unique containers for them so I access them in the array?
You need to test whether a given element is set to something before attempting to write to one of its properties.
Instead of this...
for (i = 0; i < showXMostRecentFruits; i++) {
fruitsArray[i].position = i;
}
Use this:
for (i = 0; i < showXMostRecentFruits; i++) {
if (fruitsArray[i])
fruitsArray[i].position = i;
}
You fill the array from the end, staring with element 20. Without the if (fruitsArray[i]), you're attempting to set undefined.position = i for the first 19 elements.
You could replace the showFruits function with something much more efficient:
function shiftFruits() {
if (fruitsArray.length > showXMostRecentFruits) {
fruitsArray.shift();
}
}
and updateFruitPositions only needs to update members that exist, the length is controlled by shiftFruits:
function updateFruitPositions() {
for (i = 0; i < fruitsArray.length; i++) {
fruitsArray[i].position = i;
}
}
or where forEach is supported:
function updateFruitPositions() {
fruitsArray.forEach(function(fruit, i){fruit.position = i});
}
so it only visits members that exist. And the createNewFruit has:
fruitsArray.push(new Fruit(generateName());

Categories