Home > database >  jQuery's $.each() displays only the first character of each index
jQuery's $.each() displays only the first character of each index

Time:03-14

Good day guys,

Please, I don't know what I am not doing right...

I am trying to loop through an array in jQuery and my code is as show below:

var l = [], quantity = [], all = [];
        
$.each($(data),function(key,value){
   l[key] = value.product[key];
   quantity[key] = parseInt(value.quantity[key]);
   all[key] = {y:quantity[key], label:l[key]};
})

console.log('All :' JSON.stringify(all));

I decided to console log the result just to be sure, but instead of getting the correct answer console-logged, what I saw was rather confusing...

Below is the console-logged result:

All :[{"y":6,"label":"P"},{"y":null,"label":"a"}]

And this is the expected result:

All :[{"y":632.91,"label":"Petrol"},{"y":1.0,"label":"Gas"}]

Meanwhile, this is the structure of my data:

[{amount: '1089750.00', quantity: '6604.61', product: 'Petrol', mon: '2022-02-25'},{amount: '200.00', quantity: '0.46', product: 'Kerosene', mon: '2022-02-25'},{amount: '600.00', quantity: '1.00', product: 'Gas', mon: '2022-03-01'}]

Please, any contribution, suggestion or recommendation would be greatly appreciated.

Thanks

CodePudding user response:

That is because $.each has different signature (see docs). It is $.each(data, function (index, element) which is why you have first letter from "Petrol" and second letter from "Gas" in the labe property

CodePudding user response:

I think it will help

<script> 
    let data = [{amount: '1089750.00', quantity: '6604.61', product: 'Petrol', mon: '2022-02-25'},{amount: '200.00', quantity: '0.46', product: 'Kerosene', mon: '2022-02-25'},{amount: '600.00', quantity: '1.00', product: 'Gas', mon: '2022-03-01'}]

        var l = [], quantity = [], all = [];
        
        console.log(data);
        $.each($(data),function(key,value){ 
           l[key] = value.product;
           quantity[key] = parseInt(value.quantity);
           all[key] = {y:quantity[key], label:l[key]};
        })
        
        console.log('All :' JSON.stringify(all));
</script>

CodePudding user response:

This worked

$.each(data, function(key, value) { all[key] = { y: value.quantity, label: value.product };})

Credit: Carsten Løvbo Andersen

  • Related