开发者问题收集

如何在此 javascript 对象中使用映射?不起作用

2020-07-01
71

我有这个对象:

{"act": 0, "add": "Nsnshs", "addCoord": {"_latitude": 0, "_longitude": 0}, "ble_address": "", "city": "hfhgf", "device_id": "", "last_location": {"_latitude": 0, "_longitude": 0}, "nam": "James", "personalID": "hshwwh17717", "registered_by": "fghfghfghfgh", "role": "patient", "start_treatment": {"_nanoseconds": 492000000, "_seconds": 1593634435}, "surn": "Bond", "tel": "2424554", "update_freq": 21600, "update_time": {"_nanoseconds": 492000000, "_seconds": 1593634435}}

我正在像这样打印它 console.log(documentSnapshot.data());

我想使用映射向其中添加一些新元素。我试过这个:

var dataSource = documentSnapshot.docs.map(doc => { return { ...doc.data(), doc_id: doc.id } });

但它抛出了这个错误:

TypeError: undefined is not an object (evaluating 'documentSnapshot.docs.map')

现在,我可以看到 .docs 在对象中不存在,但即使我尝试使用 .data() 它仍然显示相同的错误。那么,我在这里做错了什么?

编辑:不使用 .data() 进行打印

console.log(documentSnapshot)

{"_data": {"act": 0, "add": "Nsnshs", "addCoord": {"_latitude": 0, "_longitude": 0}, "ble_address": "", "city": "hfdfhdfgh", "device_id": "", "last_location": {"_latitude": 0, "_longitude": 0}, "nam": "James", "personalID": "hshwwh17717", "registered_by": "fghgfhfghfgh", "role": "patient", "start_treatment": {"_nanoseconds": 492000000, "_seconds": 1593634435}, "surn": "Bond", "tel": "2424554", "update_freq": 21600, "update_time": {"_nanoseconds": 492000000, "_seconds": 1593634435}}, "_exists": true, "_metadata": {"_metadata": [false, false]}, "_ref": {"_documentPath": {"_parts": [Array]}, "_firestore": {"_app": [FirebaseApp], "_config": [Object], "_customUrlOrRegion": undefined, "_nativeModule": [Object], "_referencePath": [FirestorePath], "_transactionHandler": [FirestoreTransactionHandler]}}}
1个回答

看起来您正在调用一个对象的 map 方法。map 方法仅位于数组原型上,因此这不起作用。如果您想将两个对象组合在一起以添加数据,您可以执行以下操作

将对象展开为新对象,然后向其添加数据

const newObject = {...documentSnapshot, ...theOtherObjectYouWantToCombine}

您还可以使用 for in 循环向对象添加数据,但请注意,这将覆盖您尝试应用的其他数据中具有相同名称的任何属性

for(const key in otherObject) {
documentSnapshot[key] = otherObject[key]
}
Uzair Ashraf
2020-07-01