gpt4 book ai didi

javascript - 如何有效地过滤对象的对象?

转载 作者:行者123 更新时间:2023-11-30 11:23:43 27 4
gpt4 key购买 nike

这个问题在SO中被多次提出,但都是指一个对象数组

在我的例子中,我想过滤对象的对象

假设我有这个对象:

"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
}
}

我想对此进行过滤,以便获得以下内容:

"UsersCustom": {
"w14FKo72BieZwbxwUouTpN7UQm02": {
"name": "Naseebullah Ahmadi",
"userType": "Patient",
"writePermission": false
},
"SXMrXfBvexQUXfnVg5WWVwsKjpD2": {
"name": "Levi Yeager",
"userType": "Patient",
"writePermission": false
}
}

这样做有什么意义?

请注意,这个对象“User”在现实中是巨大的(超过 1000 个条目)并且每个用户拥有的属性不仅仅是“name”、“userType”和“writePermission”。

我需要过滤用户对象的原因是这样我可以获得只有 (Patient) 的用户并获取该 Patient 的 id 在另一个对象中查找并最终将它们全部合并在一个对象中。

到目前为止我有什么

// user is the object as seen above
let Patients = users ? (
// I loop through them
Object.keys(users).map((uid, i) => {
// get individual patient
const patient = users[uid];
// check their userType
if (patient.userType === "Patient") {
let customPatient = {
uid: uid,
name: patient.name,
profession: patient.profession,
history: null,
ecg: null,
heartSound: null
};

this._healthRef(uid).then(health => {
customPatient.history = health;
return this._heartSoundRef(uid).then(HS => HS);
}).then(HS => {
customPatient.heartSound = HS;
return this._ecgRef(uid).then(a => a);
}).then(ecg => {
customPatient.ecg = ecg;
}).then(() => {
cusomPatients.push(customPatient);
})
}
})
)

我上面的解决方案虽然部分完整,但仍然效率不高而且是错误的。因为我需要每个患者的 Id 进行其他查找

更新

目前,大多数解决方案都提供遍历条目的循环,这意味着在最坏的情况下它将运行 O(n)。有没有可能比 O(n) 更快地解决?

最佳答案

使用reduce 方法你可以得到你的对象

var data = {
"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
}

};

var results = Object.keys(data).reduce(function(acc, val) {
if(data[val].userType === 'Patient') acc[val] = data[val];
return acc;
}, {});
console.log(results);

关于javascript - 如何有效地过滤对象的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com