javascript - 从嵌套对象中删除父键

标签 javascript firebase firebase-realtime-database

我正在尝试对一个对象进行排序,然后使用排序后的数据创建一个新对象。但问题是,每当我将数据推送到空数组时,它都会创建一个父键为 0,1,2... 的新对象。

{
    "0": {
        "note-1502256197947": {
            "content": "If that doesn't work, then it will reload the entire page.",
            "fav": true,
            "last_modified": "",
            "publish_date": 1502256197947,
            "slug": "starred-note",
            "title": "Starred Note"
        }
    },
    "1": {
        "note-1502108241905": {
            "categories": {
                "Learn": true,
                "Wordpress": true
            },
            "content": "Creating a embed several routes to handle Creation, Retrieval",
            "fav": true,
            "last_modified": "",
            "publish_date": 1502108241905,
            "slug": "a-new-title",
            "title": "A New Title"
        }
    }
}

这是我尝试对对象进行排序的方法:

      var noteref = firebase.database().ref(`noted${uid}/notes/`);
      var sortedKeys = [];

      noteref.orderByChild('fav').once("value", function(snapshot) {

          snapshot.forEach(function(child) {

              sortedKeys.unshift({[child.key]:child.val()}); 
              //sortedKeys[child.key] = child.val();  ***Works! but the order is lost
          });

          var newObject = {...sortedKeys};
          console.log(newObject);
      });

这就是我尝试重新创建对象的方式:

{
  "note-1502256197947": {
            "content": "If that doesn't work, then it will reload the entire page.",
            "fav": true,
            "last_modified": "",
            "publish_date": 1502256197947,
            "slug": "starred-note",
            "title": "Starred Note"

  },
  "note-1502108241905": {
            "categories": {
                "Learn": true,
                "Wordpress": true
            },
            "content": "Creating a embed several routes to handle Creation, Retrieval",
            "fav": true,
            "last_modified": "",
            "publish_date": 1502108241905,
            "slug": "a-new-title",
            "title": "A New Title"
  }

}

最佳答案

我认为您缺少一些对象的概念。如果一个对象有几个属性,那么并不意味着它们以任何方式排序。

  {
   "note-1502256197947": {...
             },
   "note-1502108241905": {...
             }
}

假设这是一个对象。该对象有 2 个属性 note-1502256197947note-1502108241905 。这并不意味着它们已排序。

关于javascript - 从嵌套对象中删除父键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589581/

相关文章:

ios - Firebase iOS SDK `setValue` 完成调用不一致

javascript - 多个捕获组同时忽略单个字符

javascript - Angular.js 将错误消息从服务传递到 Controller $scope

javascript - 需要使用子节点显示列表中的文本

firebase - 错误:在此Director小部件上方找不到正确的Provider <User>

javascript - 如何使用 React js 从 Firebase 写入和读取实时数据

javascript - 使用 Firebase 数据库的嵌套 Promise 函数

javascript - setState 的异步返回值

ios - Firebase 快照迭代顺序

android - Firebase 云消息传递 : Parsing data from the message even when the app is terminated