简体   繁体   中英

Turn jQuery array of objects into a new array

Currently my Rails controller is returning an array of objects:

var _data = [];

$.getJSON(my_url, function(data) {
  $.map(data, function(v) {
     _data.push([v.occurrences, v.period])
   });
});

console.log(_data) => []

Which when expanded looks like this:

Array[4]
 0:Object
 1:Object
 2:Object
 3:Object

And individual objects when expanded look like this:

0:Object
 occurrences:1
 period:1488499200000

I'm having trouble mapping the initial array of objects in such a way that my final result will be an array of arrays that is comprised of each objects' occurrences value and period value.

The end result should like like:

[[1488499200000, 1],[.., ..],[.., ..],[.., ..]]

So that I can use each array in a chart as an x and y axis point.

I've tried using .map, .each, (for i in ..), etc. with no luck.

EDIT:

This is my chart data:

var line_data2 = {
  data: _data,
  color: "#00c0ef"
};

$.plot("#myGraph", [line_data2], {
  grid: {
    hoverable: true,
    borderColor: "#f3f3f3",
    borderWidth: 1,
    tickColor: "#f3f3f3"
  },
  series: {
    shadowSize: 0,
    lines: {
      show: true
    },
    points: {
      show: true
    }
  },
  lines: {
    fill: false,
    color: ["#3c8dbc", "#f56954"]
  },
  yaxis: {
    show: true,
  },
  xaxis: {
    show: true,
    mode: "time",
    timeformat: "%m/%d/%Y"
  }
});

There is likely a more elegant solution than this, but this will get you the shaped array I think you are asking for.

let _data = [
  {occurrences: 1, period: 200},
  {occurrences: 3, period: 300},
  {occurrences: 6, period: 400}
];

let newData = _data.map((x)=>{
  let arr = [];
  arr.push(x.occurrences);
  arr.push(x.period);
  return arr;
});

console.log(newData);

You could take it a step further and simply loop through the object rather than hard coding the names.

let newData = _data.map((x)=>{
  let arr = [];
  for(let i in x){
    arr.push(x[i]);
  }
  return arr;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM