“testDB”是一个json文件,包含这样的数据
{
"003": {
"ID": "003",
"userID": "65489787984651423"
},
"004": {
"ID": 004
"userID": "73453212502130754"
}
}
如何检查用户 ID 是否在任何键的用户 ID 值中? 我试过了
for (let i in testDB) {
if ("73453212502130754" === testDB[i].userID) return console.log(testDB[i].ID)
}
console.log("none")
然而,当用户 ID 73453212502130754 在 JSON 数据库中时,它似乎没有做它应该在 for 循环中做的事情,我做错了什么吗?
答案 0 :(得分:0)
我可能错了,但我认为您的代码格式不正确,请尝试以下操作:
{{1}}
答案 1 :(得分:0)
以下内容将过滤掉有问题的对象:
const d={
"003": {
"ID": "003",
"userID": "65489787984651423"
},
"004": {
"ID": "004",
"userID": "73453212502130754"
}
};
const res=Object.values(d).filter(e=>e.userID==="73453212502130754");
console.log(res.length? res[0].ID : "not found!");
答案 2 :(得分:0)
目前,如果找到 ID,您将同时记录 ID,并且记录“无”。因此,理想情况下,您希望将 ID 实际存储在一个变量中,然后在循环完成后记录该 ID,或“无”。
const testDB={"003":{ID:"003",userID:"65489787984651423"},"004":{ID:"004",userID:"73453212502130754"}};
let found;
for (let key in testDB) {
if ('73453212502130754' === testDB[key].userID) {
found = testDB[key].ID;
}
}
console.log(found || 'none');
您还可以创建一个实用程序函数,您可以在其中传递数据、要搜索的属性、其值以及要返回的属性值。
const testDB={"003":{ID:"003",userID:"65489787984651423"},"004":{ID:"004",userID:"73453212502130754"}};
function findData(data, prop, value, returnValue) {
// Get the values of the object (an array) and loop over the
// objects to find where the object property matches the value
const result = Object.values(data).find(obj => obj[prop] === value);
// If `result` exists, return the required value, or "none"
return result ? result[returnValue] : 'none';
}
const result = findData(testDB, 'userID', '73453212502130754', 'ID');
console.log(result);
const result1 = findData(testDB, 'ID', '004', 'userID');
console.log(result1);