-1

I've been reading all the stuff I can find about this, but none of the solutions seems to provide the answer I need.

Specifically, I read this Access / process (nested) objects, arrays or JSON carefully, as well as dozens of other posts.

Here's what I'm trying to accomplish:

I have a large object, called allData -- that I got as a json object from MongoDB, and it contains an array of all the data from each reading.

{pitch: -7.97, roll: -4.3, temp: 98, yaw: -129.83, time: "01/22/2016 17:28:47", …}
{pitch: -8.04, roll: -4.41, temp: 97, yaw: -130.81, time: "01/22/2016 17:28:58", …}

... What I'd LIKE to do is be able to extract all the pitch readings with something along the lines of allData.pitch but obviously that doesn't work, since each data reading is in an element of the allData array. So I could go through in a loop and do allData[x].pitch but I was hoping for cleaner, faster way to do do this -- since I'll probably want to extract each type of data.

Unfortunately at this point I don't have the ability to simply request the pitch data from the db, so I get this whole set back.

One last wrinkle is that ONE of the elements of the array above is already a data object.

Community
  • 1
  • 1
Davidgs
  • 411
  • 6
  • 18
  • Likely a duplicate of http://stackoverflow.com/questions/10459917/traversing-through-json-string-to-inner-levels-using-recursive-function - if it is, feel free to delete your question – mplungjan Jan 23 '16 at 17:30
  • 2
    `var pitches = allData.map(function(o) { return o.pitch; });` – Andreas Jan 23 '16 at 17:31
  • Sorry, wasn't clear in the original question ... I'd like to get back the pitches and the data/time they were recorded so that I can graph them accordingly. – Davidgs Jan 23 '16 at 17:34
  • @Andreas +1 also `allData.map(o => o.pitch)` :) – Nebula Jan 23 '16 at 17:43

2 Answers2

2

You can utilise Array.prototype.map() for this

var pitches = allData.map(function(d) {
                  return {
                      "pitch": d.pitch,
                      "time": d.time
                  };
              });
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

If you can't control the data returned from the server (i.e., to only retrieve the pitch values you want), you are going to have to loop through to get them all.

Tocacar
  • 475
  • 3
  • 12