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

时间:2018-11-29 10:03:58

标签: javascript arrays angularjs json angular

这是我的小提琴:DEMO1

以下函数提取键和值,并将其存储在新数组中。这适用于对象(json2和json3),而不适用于存在对象数组(json1)的情况

是否可以将一组键值对组合为一个对象,然后将该对象推入数组? 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];
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样映射数据数组:

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

http://jsfiddle.net/fghjtsnm/