0

How to convert the object { CntDay: 0, CntMonth: 2, CntYear: 4 } to the array [ 0, 2, 4 ]?

I am getting my data in the events array but I need the array to not form like { CntDay: 0, CntMonth: 2, CntYear: 4 } but simply like [ 0, 2, 4 ].

function createChartWinLoss() {
  var events = [];

  $.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    url: "Dashboard.aspx/NewChart",
    success: function(data) {
      $.each(data.d, function(i, v) {
        events.push({
          CntDay: v.CntDay,
          CntMonth: v.CntMonth,
          CntYear: v.CntYear
        });
      })
      ChartProp(events)
    }
  });
}

function ChartProp(events) {
  var a = $.map(events, function(value, index) {
    return [value];
  });
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212). – Sebastian Simon May 20 '20 at 23:04

2 Answers2

0

You just need to push a different object to the events array.

function createChartWinLoss() {
  var events = [];
  $.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    url: "Dashboard.aspx/NewChart",
    success: function(data) {
      $.each(data.d, function(i, v) {
        // here push an array, instead of an object
        //events.push({
        //  CntDay: v.CntDay,
        //  CntMonth: v.CntMonth,
        //  CntYear: v.CntYear
        //});
        
        events.push([
          v.CntDay,
          v.CntMonth,
          v.CntYear
        ])
        
      })
      
      ChartProp(events)
    }
  });
}

function ChartProp(events) {
  //var a = $.map(events, function(value, index) {
  //  return [value];
  //});
  
  console.log({events: events})

}
mhSangar
  • 457
  • 3
  • 12
0

Just use Object.values(data). It directly creates an array of all the values present in your object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Berk Kurkcuoglu
  • 1,453
  • 1
  • 9
  • 11