64Bit1990
64Bit1990

Reputation: 330

javascript add key value pair to array checking if exists

In a Laravel application I need to add chartjs graphs in the dashboard. In particular one of the graphs must be stacked bar. On the x axis I have the labels represented by taxes, while on the y axis I have the 3 categories of values (paid, unpaid, partially paid). I then then defined 3 empty arrays A, B, C which I pass to the graph with the correct data. So to populate the graph I use a script with which I pass the data. My problem is that the paid, unpaid, partial paid arrays don't have the same length and are composed with the structure:

arrayX = [{total: value, tax: "Description1"},{},...,{total: value, tax: "DescriptionN"}];

while the array of labels=["Description",.........,"DescriptionN"];

I would need to cycle on the array of labels, if the value is present in the arrayX then I set for A.push(arrayX.total) otherwise A.push(0.00);

All this while maintaining the order of the elements.

Do you have any suggestions or advice? Is it possible with Javascript to do this?

Upvotes: 0

Views: 42

Answers (1)

James
James

Reputation: 22237

You can map over labels trying to find a match in arrayX.

   const A = labels.map(l => {
      let data = arrayX.find(el => el.tax === l);
      if (!data)
        return 0;
    
      return data.total;
    });

Upvotes: 1

Related Questions