简体   繁体   中英

How to convert array object with nested object complex to CSV file

I need some help. I want to loob array nested object as below Figure1 and get data become to array2D to convent data to CSV file but I don't understand much to loop my data to get details become to array2D. Or anyone has other ways to export data to CSV file with output like this.


var data = {
  deviceA: {
    smokeSensor: [
      {
        '190501': {
          '0001': 200,
          '0002': 300
        },
      },
      {
        '190502': {
          '0001': 20,
          '0002': 30
        },
      }
    ],
    fireSensor: [
      {
        '190501': {
          '0001': 700,
          '0002': 750
        },
      },
      {
        '190502': {
          '0001': 780,
          '0002': 630
        },
      }
    ]
  },
  deviceB: {
    smokeSensor: [
      {
        '190601': {
          '0001': 100,
          '0002': 110
        },
      },
      {
        '190602': {
          '0001': 120,
          '0002': 130
        },
      }
    ],
    fireSensor: [
      {
        '190601': {
          '0001': 600,
          '0002': 522
        },
      }
    ]
  },
};

This is output that I want to get with array2D to throw it to function convert array2D to CSV file.

const rows = [
  ["DeviceA"]
  ["Date/Time", "smokeSensor", "fireSensor"],
  ["190501 00:01", "200", "700"],
  ["190501 00:02", "300", "750"],
  ["190502 00:01", "20", "780"],
  ["190502 00:02", "30", "630"],
  [""],
  ["DeviceB"],
  ["Date/Time", "smokeSensor", "fireSensor"],
  ["190501 00:01", "100", "600"],
  ["190501 00:02", "110", "522"],
  ["190502 00:01", "120", ""],
  ["190502 00:02", "130", ""],
];

This is my code I've tried to loop but I'm pretty dazed once looping each loop to get each detail of value for date time. Unfortunately, I got the details that was not as desired.

var dataCSV = []
var mdbName = []
var header = ['DateTime']
var content = []
var dateTime = ''
for (var deviceId in data) {
  mdbName.push(deviceId)
  for (var sensorName in data[deviceId]) {
    header.push(sensorName)
    // console.log(data[deviceId][sensorName]);
    Object.keys(data[deviceId][sensorName]).forEach(item => {
      let date = data[deviceId][sensorName][item]
      for (var key3 in date) {
        // console.log(key3)
        for (var key4 in date[key3]) {
          dateTime = key3 + key4
          // console.log(deviceId + ': ' + sensorName + ': ' + dateTime + ':' + date[key3][key4])
          content.push(date[key3][key4])
        }
      }
    })
  }
}
dataCSV.push(mdbName)
dataCSV.push(header)
dataCSV.push(content)
console.log('End: ', dataCSV)

This is my bad output:

[ 
  [ 'deviceA', 'deviceB' ],
  [ 'DateTime', 'smokeSensor', 'fireSensor', 'smokeSensor', 'fireSensor' ],
  [ 200, 300, 20, 30, 700, 750, 780, 630, 100, 110, 120, 130, 600, 522 ] 
]

You could go with something like the following function. The approach is to iterate over the structure's keys, group sensor values on time and hour/minute strings and dump each device into the result row. Some padding is done to ensure rows are the same width, per your spec.

A bit of cleanup wouldn't hurt, but it seems to get the job done (I assume your DeviceB output is a typo on "190501" , which should be "190601" based on your input data).

 var data = { deviceA: { smokeSensor: [ { '190501': { '0001': 200, '0002': 300 }, }, { '190502': { '0001': 20, '0002': 30 }, } ], fireSensor: [ { '190501': { '0001': 700, '0002': 750 }, }, { '190502': { '0001': 780, '0002': 630 }, } ] }, deviceB: { smokeSensor: [ { '190601': { '0001': 100, '0002': 110 }, }, { '190602': { '0001': 120, '0002': 130 }, } ], fireSensor: [ { '190601': { '0001': 600, '0002': 522 }, } ] }, }; const dataToCSV = data => { const rows = []; for (const device in data) { rows.push( [device.replace(/^./, m => m.toUpperCase())], ["Date/Time", ...Object.keys(data[device])] ); const groups = {}; let longest = 0; for (const sensor in data[device]) { for (const time of data[device][sensor]) { const k = Object.keys(time)[0]; for (const hm in time[k]) { const groupKey = `${k} ${hm.replace(/(\\d\\d)(\\d\\d)/, "$1:$2")}`; if (!(groupKey in groups)) { groups[groupKey] = [groupKey]; } groups[groupKey].push("" + time[k][hm]); longest = Math.max(longest, groups[groupKey].length); } } } for (const group of Object.values(groups)) { while (group.length < longest) { group.push(""); } rows.push(group); } rows.push([""]); } return rows.slice(0, -1); }; console.log(dataToCSV(data)); 

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