简体   繁体   English

从json对象中提取键值对并将其分组-Javascript

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

Here is my fiddle : DEMO1 这是我的小提琴: 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) 这适用于对象(json2和json3),而不适用于存在对象数组(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/ http://jsfiddle.net/fghjtsnm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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