How to loop and push objects values to array?

rob.m

I have a json like:

data: (46) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Province/State: "Anhui"
Country/Region: "Mainland China"
Lat: 31.8257
Long: 117.2264

Now data has

data: Array(46)
0: {date: "1/22/20", Recovered: 0, Deaths: 0, Confirmed: 1}
1: {date: "1/23/20", Recovered: 0, Deaths: 0, Confirmed: 9}
2: {date: "1/24/20", Recovered: 0, Deaths: 0, Confirmed: 15}
3: {date: "1/25/20", Recovered: 0, Deaths: 0, Confirmed: 39}
4: {date: "1/26/20", Recovered: 0, Deaths: 0, Confirmed: 60}
5: {date: "1/27/20", Recovered: 0, Deaths: 0, Confirmed: 70}
6: {date: "1/28/20", Recovered: 0, Deaths: 0, Confirmed: 106}

And I have plenty objects in the json, I loop and push coordinates like this:

let coords = [];

getVirusData();

function getVirusData() {
  getAvailableDatasets()
    .then(combineDatasets)
    .then(data => { // It's asynchronous
      coords.push.apply(coords, data.map(item => item.Lat + "," + item.Long));
    }).then(function(entry) {
      for (var a = 0; a < coords.length; a++) {
        var pin = coords[a].split(',');
        var latLng = new google.maps.LatLng(pin[0], pin[1]);
        var marker = new google.maps.Marker({
          position: latLng,
          map: map
        });
      }
    });
  }

That works but I need to also push each date for each object into an array, should be i believe an associative array tho since the dates are related to those particular coordinates and do so for each object and also "confirmed", "Recovered" and "Deaths" should go to their own array but related to each object

Desired output would be an array like

obj = ["31.8257,117.2264"]["22/02/20", "24/02720"]["recovered 1", "recovered 3"]

But I don't understand how I could do that for each object

Mhmdrz_A

Here is a working fiddle for filtering your inputs based on dates from the slider and date attribute on the input data:

https://jsfiddle.net/ku16vapg/5

let virusData;
let virusDataCopy;
getVirusData();

function getVirusData() {
  getAvailableDatasets()
    .then(combineDatasets)
    .then((r) => {
      try {
        virusData = JSON.Parse(r);
      } catch (e) {
        virusData = r;
      }
      initUI(virusData);
    })
}



function initUI(initialDataSet) {
  function dateToTS(date) {
    return date.valueOf();
  }

  function tsToDate(ts) {
    var d = new Date(ts);
    return d.toLocaleDateString(lang, {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  }

  let dataSetCopy = [];
  initialDataSet.forEach(ds => {
    ds.data.forEach(obj => {
      dataSetCopy.push(obj.date)
    })
  })
  dataSetCopy.sort((a, b) => Date.parse(a) - Date.parse(b));
  console.log(dataSetCopy)

  let lang = "en-US";

  $("#demo_4").ionRangeSlider({
    skin: "big",
    type: "double",
    grid: true,
    min: dateToTS(new Date(dataSetCopy[0])),
    max: dateToTS(new Date(dataSetCopy[dataSetCopy.length - 1])),
    from: dateToTS(new Date(dataSetCopy[3000])),
    to: dateToTS(new Date(dataSetCopy[7000])),
    prettify: tsToDate,
    onFinish: function(data) {
      let filtererdData = virusData.map(vd => {
        return { ...vd,
          data: vd.data.filter(obj => {
            objDataTS = Date.parse(obj.date);
            return (objDataTS < data.to) && (objDataTS > data.from)
          })
        }
      })
      updateUI(filtererdData)
    },
  });
  updateUI(initialDataSet)
}

function updateUI(dataSet) {
  document.querySelector("pre").textContent = JSON.stringify(dataSet, null, 2)
};



function getAvailableDatasets() {
  return $.getJSON('https://api.github.com/repos/CSSEGISandData/COVID-19/contents/csse_covid_19_data/csse_covid_19_time_series')
    .then((files) => {
      return Promise.all(
        files.filter(file => /^time_series_19-covid-.+\.csv$/.test(file.name))
        .map(file => getDataset(file.download_url))
      );
    })
    .catch(function(err) {
      console.log(err);
    })
}

function getDataset(url) {
  return $.ajax(url)
    .then(csv => {
      const output = Papa.parse(csv, {
        header: true, // Convert rows to Objects using headers as properties
        dynamicTyping: true, // Convert some fields to Numbers automatically
      });
      if (output.data) {
        const labelMatches = url.match(/time_series_19-covid-(.+)\.csv$/);
        const label = labelMatches ? labelMatches[1] : "Untitled";

        const formatted = output.data.map(area => {
          const obj = {};

          Object.keys(area).forEach(key => {
            if (/^\d+\/\d+\/\d+$/.test(key)) {
              obj[key] = {
                date: key,
                [label]: area[key]
              };
            } else {
              obj[key] = area[key];
            }
          });

          return obj;
        });



        return formatted;
      } else {
        console.log(output.errors);
      }
    });
}

function combineDatasets(datasets) {
  if (datasets.length) {
    const combined = datasets.reduce((result, dataset, i) => {
      if (i === 0) {
        return result;
      }
      dataset.forEach(area => {
        // Look for area with same coordinates
        let existingArea = result.find(a => a.Lat === area.Lat && a.Long === area.Long);
        if (!existingArea) {
          result.push(area);
        } else {
          const dates = Object.keys(area).filter(key => /^\d+\/\d+\/\d+$/.test(key));
          dates.forEach(date => existingArea[date] = Object.assign(area[date], existingArea[date]));
        }
      });
      return result;
    }, datasets[0]);

    return combined.map(area => {
      const obj = {
        data: []
      };

      Object.keys(area).forEach(key => {
        if (/^\d+\/\d+\/\d+$/.test(key)) {
          obj.data.push(area[key]);
        } else {
          obj[key] = area[key];
        }
      });

      return obj;
    });
  } else {
    throw "No datasets were found";
  }
}
<!--Plugin CSS file with desired skin-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/css/ion.rangeSlider.min.css" />

<!--jQuery-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<!--Plugin JavaScript file-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/js/ion.rangeSlider.min.js"></script>
<input id="demo_4" />
<pre></pre>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to loop over objects and push the keys into an array?

How to sum values of objects and push it in an array

How to push values correctly into an array of objects

How to loop through an array of Firebase Firestore documents and push values into array

how to push objects in to an array?

how to loop trough an objects and dynamically push items to array in javasript

How to push an array with objects into an array

PHP push objects to array from foreach loop

PHP - How to loop through array of objects and sum values

How to calculate values differences in an array of objects without a for loop, in JavaScript?

how to push objects into array in ReactJS

How to push an element to an array in a loop

How to merge two array of objects containing different values of same key, and also push new object into the array?

How to find duplicate values in object and push in array to create distinct array of objects in Angular8

How to push selected objects from an array of objects into one array of objects

How to push multiple values in array?

how to push the array values in javascript

How to push an object into an array nested in an array of objects?

How to push array inside array of objects?

How to push an array into an array of objects using AngularJs

Comparing 2 objects' values and push the values to one object array

how to collect data from json objects with multiple keys and push all values to single key:value array

How can I push multiple values from inputs in a form to an array of objects in mongoose.model?

How do I calculate values of each objects in two different arrays and push to a new array?

How to properly use dataLayer.push(), to update values, of nested objects, in an array?

Loop over an array of objects and format values

How to loop over array of objects?

How to create an array of objects with a for loop

Can't get values from loop to push to array outside of loop