Search code examples
javascriptarraysobjectget

Multiply All Values By Single Value In Arrays Of GET Updated Data Object


I have a JSON object that stores data from an API GET request. Each object in the object has two arrays. I need to multiply the second array (the y value). The data is stored like so:

  var apiData = {
  'id1': {
    x: [],
    y: []
  },
  'id2': {
    x: [],
    y: []
  },
  'id3': {
    x: [],
    y: []
  },

Etc. There are 50 arrays that need each of their values multiplied.

I understand I need to do something like this:

var multiplyFunction = function() {
  for (var i = 0; i < apiData.length; i++);
  [do something]
}

How exactly can I multiply all the elements in the y arrays by a single number (like 1,000), though? I've looked at a few other topics and it wasn't clear. Thanks!

UPDATE:

I've found a solution by multiplying the values as they are being pushed to the array from the API data. Like so:

  for (var i = 0; i < data.length; i++) {
    apiDataObject[id].x.push(data[i][0]);
    /* Multiply each value by 1,000 to convert units. */
    apiDataObject[id].y.push(data[i][1] * 1000);
  }

This is also better for browser compatibility.


Solution

  • I've found a solution by multiplying the values as they are being pushed to the array from the API data. Like so:

          for (var i = 0; i < data.length; i++) {
            apiDataObject[id].x.push(data[i][0]);
            /* Multiply each value by 1,000 to convert units. */
            apiDataObject[id].y.push(data[i][1] * 1000);
          }
    

    This is also better for browser compatibility.