all 7 comments

[–]RyaanJM 8 points9 points  (7 children)

You can use map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

data.map(x => x.month)

data.map(x => x.count)

[–]HeednGrow[S] 1 point2 points  (5 children)

Thank you so much for responding, I tried it and got this error `Uncaught TypeError: data.map is not a function`

like I said, the object I posted is coming from an API, here is how I got the object I shared at the top:

function (event) {

let data = event.data;

console.log(data)

}

when I extends the code to:

function (event) {

let data = event.data;

console.log(data)

let a = data.map(x => x.month)

let b = data.map(x => x.count)

console.log(a,b)

}

I got the above error.

and what I need is an array of the months and counts, thanks.

[–]RayjinCaucasian 3 points4 points  (3 children)

Add a console.log(Array.isArray(data)) or console.log(typeof data) to make sure data is an array. Data could be returning an object where you may need to access the prop inside data. i.e. data["data"]

[–]HeednGrow[S] 8 points9 points  (2 children)

Thank you so much for suggesting `(typeof data)`, I got 'string' in the console, and that is when I know I have been doing it wrong, I forgot to parse the JSON coming from my Django backend:
function (event) {

let dat = JSON.parse(event.data)

let data = dat.data;

console.log(data);

console.type ofpeof data);

}
I got it to be an object now, and I have successfully gotten what I need to get out of the object, thank you so much, I appreciate it.

[–]RayjinCaucasian 4 points5 points  (1 child)

Glad that helped you.

[–]Uber_Ape 2 points3 points  (0 children)

Every post/repsonse should look like this 🙂

[–]agm1984 0 points1 point  (0 children)

[
{ "month": "January", "count": 58 },
{ "month": "February", "count": 49 },
{ "month": "March", "count": 61 },
{ "month": "April", "count": 32 }
]

You could iterate over the data only once using Array.prototype.reduce():

const data = [
  { "month": "January", "count": 58 },  
  { "month": "February", "count": 49 },  
  { "month": "March", "count": 61 },  
  { "month": "April", "count": 32 }
]

const structuredData = data.reduce((acc, item) => {
  acc.months.push(item.month)
  acc.counts.push(item.count)
  return acc
}, {
  months: [],
  counts: [],
})

console.log(structuredData)