【发布时间】:2018-03-26 16:27:17
【问题描述】:
目前,我正在调用一个返回大约 1,000 个对象的数据库。
我在将对象发布给用户之前对其进行过滤;可以想象,过滤 1000 个对象需要很长时间。
我现在的过滤器是这样的:
if (!isPatient && this._isMounted) {
this.setState({
Users: JSON.parse(JSON.stringify(userSnapData), (k, v) => !v.type || (
v.type === "Patient" && (_.has(userSnapData[this.state.authUserUID], `Patients`) ? _.has(userSnapData[this.state.authUserUID][`Patients`], k) : true)
) ? v : void 0)
})
}
其中userSnapData 是从数据库中检索的数据。
/*
* this is basically saying, filter the object where the type is "Patient"
* and it has nested "Patients" object
*/
JSON.parse(JSON.stringify(userSnapData), (k, v) => !v.type || (
v.type === "Patient" && (_.has(userSnapData[this.state.authUserUID], `Patients`) ? _.has(userSnapData[this.state.authUserUID][`Patients`], k) : true)
) ? v : void 0)
这里的主要问题是如何并行过滤数据,以便在过滤对象的同时,我想立即展示这一点,而不是等待整个 1000 个对象都被过滤。
是否可以使用某种Data.map(async element => {...}) 或类似的东西?
更新
假设我得到这样的数据:
"Users": {
"w14FKo72BieZwbxwUouTpN7UQm02": {
"name": "Naseebullah Ahmadi",
"userType": "Patient",
"writePermission": false
},
"SXMrXfBvexQUXfnVg5WWVwsKjpD2": {
"name": "Levi Yeager",
"userType": "Patient",
"writePermission": false
},
"VoxHFgUEIwRFWg7JTKNXSSoFoMV2": {
"name": "Ernest Kamavuako",
"userType": "Doctor",
"writePermission": true
},
"hFoWuyxv6Vbt8sEKA87T0720tXV2": {
"name": "Karla Stanlee",
"userType": "Doctor",
"writePermission": true
}
}
我通过userType 过滤它们并将其作为对象返回,而不是数组。这是过滤它们后的主要问题之一,我需要将数据作为对象和对象数组返回。
【问题讨论】:
-
为什么是
JSON.parse(JSON.stringify(userSnapData)?看起来您正在将对象转换为字符串并返回。这似乎没有太大意义。 -
你为什么要那样做
JSON.parse和JSON.stringify?这可能就是您的性能瓶颈所在。 -
1000 个对象是非常小的数量。瓶颈在其他地方。
-
去掉来回的Json解析,看看性能如何。如果在那之后有问题,那么可能考虑过滤 before 从服务器返回(如果可能的话)。
-
你为什么不直接使用
filter?
标签: javascript object filter parallel-processing lodash