【发布时间】:2018-09-04 13:35:30
【问题描述】:
从服务器加载 JSON 时,我需要创建对象。对象并不总是事先存在。因此,我必须在添加新级别之前检查每个级别是否存在。有没有更好的方法来做到这一点,那么下面的方法:
var talkerId = commentDB.val().to;
var commentId = commentDB.val().id
if (!store.talkers.hasOwnProperty(talkerId)) {
store.talkers[talkerId] = {}
}
if (!store.talkers[talkerId].hasOwnProperty(comments)) {
store.talkers[talkerId] = { comments: {} };
}
if (!store.talkers[talkerId].comments.hasOwnProperty(commentId)) {
store.talkers[talkerId].comments[commentId] = {}
}
store.talkers[talkerId].comments[commentId].author = commentDB.val().author;
【问题讨论】:
-
能不能简单的从服务器返回JSON,然后用
JSON.parse()转换成对象? -
我无法从服务器返回,因为我加入了两个数据字段,并在客户端创建了组合的JSON。
-
所以你对服务器进行了 2 次调用,每个都进行了一次 DB 调用,然后你将 2 个数据集返回给客户端并将它们合并到一个对象中?
-
@31piy,它完成了工作:-)
标签: javascript json object properties nested