简体   繁体   中英

Extract key value pairs from json object and group them - Javascript

Here is my fiddle : DEMO1

The following function extracts the keys and values and stores it in a new array. This works right for objects(json2 and json3) and not when there is an array of objects (json1)

Is there a way to group a set of key value pairs into an object and then push that object into the array? Desired output : [{"timestamp":1540457640,"speed":"70"},{"timestamp":1541383353,"speed":"80"},{"timestamp":1541383353,"speed":"70"},{"timestamp":1542256083,"speed":"70"}]

function iterate(obj) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        iterate(obj[property]);
        if (isNaN(Number(property))) {
          if ((Array.isArray(obj[property])) && (typeof obj[property][0] != "object")) {
            simpleArrayKeys[property] = obj[property];
          }
        }
      } else {
        if (isNaN(Number(property))) {
          simpleArrayKeys[property] = obj[property];
        }
      }
    }
  }
}

You can map the data array like so:

var output = json1.data.allStreamingData.map(d => {
  return {
    "timestamp": d.timestamp,
    "speed": d.streamData.speed
  }
})

http://jsfiddle.net/fghjtsnm/

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