将Firebase快照递归转换为阵列无法正常工作

时间:2018-08-27 20:45:44

标签: javascript arrays firebase recursion firebase-realtime-database

我的Firebase数据库具有以下结构:

enter image description here

我需要使用特殊结构获取所有数据的数组。这是我的方法:

const isObject = obj => {
    return Object.prototype.toString.call(obj) === '[object Object]' ? true : false;
};

function snapshotToArray(snapshot) {
    var returnArr = [];

    snapshot.forEach(function(childSnapshot) {
        var item = childSnapshot.val();
        item.key = childSnapshot.key;

        returnArr.push(item);

        if (isObject(item)){
            returnArr = returnArr.concat(snapshotToArray(childSnapshot));
        }

    });

    return returnArr;
};

并命名为:

snapshotToArray(snapshot); // 'snapshot' is the data from database in a snapshot format

获取:

[ { 'Diciembre-2018': { '-LJV5UxepDNSR5yUCDbf': [Object] },
    'Julio-2018': { '-LJUt8yTjpK3oq2wRd_g': [Object] },
    key: '2018' },
  { '-LJV5UxepDNSR5yUCDbf':
     { pin: 'mi-pin-dic',
       timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)' },
    key: 'Diciembre-2018' },
  { pin: 'mi-pin-dic',
    timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
    key: '-LJV5UxepDNSR5yUCDbf' },
  'mi-pin-dic',
  'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
  { '-LJUt8yTjpK3oq2wRd_g':
     { pin: 'mi-pin-julio',
       timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' },
    key: 'Julio-2018' },
  { pin: 'mi-pin-julio',
    timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)',
    key: '-LJUt8yTjpK3oq2wRd_g' },
  'mi-pin-julio',
  'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' ]

但是如您所见,在第3次和第5次迭代中,它会获得额外的数据:

'mi-pin-dic',
  'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',

'mi-pin-julio',
  'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)'

我的问题:

如何避免此问题?有什么想法吗?

0 个答案:

没有答案