I am trying to push data into array in this code
let eyesData = [];
const pushFaceData = (
{ rightEyeOpenProbability },
i
) => {
//Value is getting printed in console but not getting pushed
//console.log(rightEyeOpenProbability);
eyesData.push(rightEyeOpenProbability);
};
const renderFaces = () => {
faces.map(pushFaceData);
};
console.log(eyesData);
faces is stream of data that updates itself in every 100ms so eyesData array should also be getting populated on each 100ms but in console, eyesData is always getting printed with empty value.
Array[]
Array[]
.
.
If rightEyeOpenProbability is printing to the console, then there is no reason your code should be failing...
You are probably changing eyesData somewhere. For example, if you made a typo when checking its length, you could be erasing it:
if( eyesData.length = 0 ) { ... } //this line would erase eyesData[]'s contents
Related
how can I get all this array in one array without getting it one after the other like this in the code below? i mean saving the whole data inside one variable without giving a specific index of the array
here's the code
const favoriteProductone = data?.getAllLikeProduct[0]
const favoriteProductTwo = data?.getAllLikeProduct[1]
const favoriteProductThree = data?.getAllLikeProduct[2]
console.log(favoriteProductone?.Like[0])
console.log(favoriteProductTwo?.Like[0])
console.log(favoriteProductThree?.Like[0])
Just iterate the array like so:
if (!data) {
throw "data is falsy - there is nothing to process";
}
data.getAllLikeProduct.forEach(p => {
console.log(p.Like[0])
});
It happens that there is an array of objects that within each object has a property with an array. This array, in the same cycle, is parsed sometimes correctly and other times incorrectly. It is observed in the image that inside the object the array has elements, however sometimes it shows length 0 and other times it shows a correct length.
The problem that I present is not only in the browser console. When the code processes the array, it actually considers it to have array 0 when it does have elements in it.
Basically what happens is that it analyzes the length of an array to see if it needs to add or remove elements, however due to asynchrony that I don't understand, there are times when in the same cycle it considers that there are elements and other data sets that also has data; it parses it as if it had no data.
I have created promises, async await, observables and nothing works to parse the array correctly.
The const cantidad_que_hay parses the length sometimes correctly and sometimes incorrectly in the same loop. It's not just a console issue, it does indeed parse it incorrectly, independent of the browser console.
Promise.all(promesa_procesandoimagenes)
.then( (data: any) => {
console.log('ViendoSiSuscribeSirve Promise.all.data', data)
data.forEach( (valor:any, indice:any) => {
of(valor).pipe( delay(0) )
.subscribe( data2 => {
console.log('ViendoSiSuscribeSirve data2', data2 )
console.log('ViendoSiSuscribeSirve data2.item_imagen[0]', data2.item_imagen[0])
console.log('ViendoSiSuscribeSirve data2.item_imagen[1]', data2.item_imagen[1])
console.log('ViendoSiSuscribeSirve data2.item_imagen[1].flat(2)', data2.item_imagen[1].flat(5))
console.log('ViendoSiSuscribeSirve data2.item_imagen[1].flat(2).length **length**', data2.item_imagen[1].flat(2).length)
console.log(
'ViendoSiSuscribeSirve this.dinamicMap.default_images[item_unitario]',
this.dinamicMap.default_images[data2.item_imagen[0]]
)
const cantidad_que_hay = data2.items.flat().length // SuperAvanceDesktop: 2
console.log('ViendoSiSuscribeSirve data2.item_imagen[1] **length**', cantidad_que_hay)
const array_imagenes_default = this.dinamicMap.default_images[data2.item_imagen[0]]
const nombre_seccion = data2.item_imagen[0]
if (cantidad_que_hay > data2.min && cantidad_que_hay < data2.max){
// Si está dentro del rango, return ok
objeto_imagenes_listo[nombre_seccion] = data2;
}
/* data2.min */
if( (data2.min - cantidad_que_hay ) > 0 ){
// PONER: (Poner data2.min - data2.item_imagen[1].length)
const cantidad_a_poner = data2.min - cantidad_que_hay;
if(nombre_seccion == 'super_avance_desktop'){
console.warn('ViendoSiSuscribeSirve [...data2.item_imagen[1]]', [...data2.item_imagen[1]])
console.warn('ViendoSiSuscribeSirve', cantidad_que_hay)
console.warn('ViendoSiSuscribeSirve data2.item_imagen[1].flat(2)', data2.item_imagen[1])
console.warn('ViendoSiSuscribeSirve data2.item_imagen[1].flat(2)', data2.item_imagen[1].flat())
}
array_imagenes_default.some( (imagen:any, indice:any) => {
if( indice == (cantidad_a_poner - 1 ) ){
// Listo
objeto_imagenes_listo[nombre_seccion] = data2;
}else{
// Agregar
data2.item_imagen[1].push( {imagen: imagen} )
}
} )
}
if( (data2.max - cantidad_que_hay) < 0 ) {
// SACAR : (Poner data2.max - data2.item_imagen[1].length)
const cantidad_a_sacar = data2.max - cantidad_que_hay;
data2.item_imagen[1].splice(1 , cantidad_a_sacar)
objeto_imagenes_listo[nombre_seccion] = data2;
}
}) // Fin Subscribe
} )
} ) // ** Fin PromiseAll
Image showing correct analysis of array length
Image showing incorrect parsing of array length
I'm trying to refactor an object into an array to fit an API that I have to use.
function buildObject(data) {
console.log(data) // correct ouput
var jsonLayers = Object.entries({...data}).map(([k, v]) => {
console.log(`value : ${v}`) // correct output
return {
label: k,
pointMap: v,
color: v.layerColor?v.layerColor:tabList[tabList.map(i => i.tabName).indexOf(k)].layerColor?tabList[tabList.map(i => i.tabName).indexOf(k)].layerColor:defaultPOILayerColor,
}}
)
console.log(jsonLayers) // incorrect output
return jsonLayers
}
I have 2 scenarios in which I call this function but with the same data (console.log(data) logs the exact same result).
In the first scenario I obtain the desired result and in the second the pointMap attribute is an empty Array.
In the case where it does not work the console.log(`value : ${v}`) logs the correct value but when I log console.log(jsonLayers) the attribute pointMap is empty.
Any ideas on why this happens ?
Edit: as mentionned below this code works with sample data so I suppose this must comes to how the function is called. Everything runs in a UWA widget with jQuery
So for the context here is an idea of how they are called in both cases :
var data = {
a: { tabName: "tab1", layerColor: 1 },
b: { tabName: "tab2", layerColor: 2 },
};
$('#button1').on('click', function() {
ExternalAPI.Publish('some-external-address', buildObject(data));
});
$('#button2').on('click', function() {
let jsonData = buildObject(data);
//some manipulations of jsonData
ExternalAPI.Publish('some-external-address', jsonData);
});
It works on button1 but not on button2, they are clicked are at a different moment but data contains the same object when both are clicked
Edit2 :
Found the issue,
In the manipulations of jsonData I accidentally use slice(1,1) instead of splice(1,1) which empties the array.
What drove me crazy is that this modification was perform after the log but the var was log with the modification.
At least I learnt that spread operator does not deepcopy
Found the issue,
In the manipulations of jsonData I accidentally use slice(1,1) instead of splice(1,1) which empties the array.
What drove me crazy is that this modification was perform after the log but the var was log with the modification
I am building an App and I have a problem inside a for loop.
Inside my function I got two arrays as arguments (payload.data.start and payload.data.end) and I am trying to push it inside the mongodb.
My code looks like this
async function emplaceAval (state, payload, blockInfo, context) {
for(var i=0 ; i<payload.data.start.length ; i++) // start and end have the same length
{
const user =await User.findOne({ 'account': payload.data.account })
user.availability.push({start: new Date(payload.data.start[i]+'Z') , end: new Date(payload.data.end[i]+'Z')});
await user.save();
}
}
The problem is that lots of times I lose data. By losing data I mean that the i changes before user.save take place.
I consider to use forEach , but I have two arrays that need to be save together , so I cant .
The second solution I thought is to create an index array . For example if the length of my arrays is 5 , I will create an indexTable=[0 , 1 , 2 , 3 , 4 ] and I will use asyncForEach to this array. But i dont think that this solution is the preferable.
Any ideas? Thanks in advance
From what I can see here the looping is completely unneccesary. MongoDB has a $push operator which allows update of an array without retrieving the document first. This also has an $each option to allow a list of elements to be "pushed" in the singe update.
In short this is just one request and response to the server to await:
// Transpose to array of objects for update
let availability = payload.data.start.map((e,i) =>
({ start: new Date(e+'Z'), end: new Date(payload.data.end[i] + 'Z') })
);
try {
// Perform the **one** update request
let response = await User.updateOne(
{ 'account': payload.data.account },
{ '$push': { 'availability': { '$each': availability } } }
);
// maybe check the response
} catch(e) {
// do something with any error
}
That's all you need do. No need to "loop" and so much less overhead than going back and forth to the server retrieving a document and making changes then putting the document back.
I've a javascript file that passes an argument to the backend php file. Which will try to find out which values are true.
This is the passed parameter,
{"2":true,"3":false,"4":true}
This is the php code that will extract the keys of the True arrays,
<?php
print_r(loop_filters($_REQUEST['filters']));
// Functions starts here
function loop_filters($filters)
{
$filters = json_decode($filters);
// return $filters;
$filter_array = [];
while($filter_key = current($filters))
{
if($filter_key === true)
{
$filter_array[] = key($filters);
}
next($filters);
}
return $filter_array;
}
?>
However the output is
Array ( [0] => 2 )
Why is it not detecting 4 as true and give an output like
Array ( [0] => 2 , [1] => 4)
What's wrong and how can I fix it? Thanks
Your code doesn't work simply because of this:
while($filter_key = current($filters))
Because in the second iteration your value will be: FALSE and as we all know:
while(FALSE)
This won't run, so you end the loop after the first iteration already.
How to solve it? Just simply remove the next() calls and replace the while loop with a foreach loop, e.g.
function loop_filters($filters) {
$filters = json_decode($filters);
foreach($filters as $key => $filter_key) {
if($filter_key === true) {
$filter_array[] = $key;
}
}
return $filter_array;
}
Rizier123 solves the issue with your code, however for this specific case, to get the keys of the true values it's much simpler:
$filter_array = array_keys($filters, true, true);