gpt4 book ai didi

javascript - 如何访问嵌套对象中的键

转载 作者:行者123 更新时间:2023-11-28 16:55:02 24 4
gpt4 key购买 nike

{
"5def224170a3ec0d90dbb89a": {
"_id": "5def224170a3ec0d90dbb89a",
"username": "dhruv1999",
"fullname": "dhruv parmar",
"email": "dhruv@gmail.com",
"phone": "7045691556",
"password": "$2a$10$UOk8E4fbkkZvSRSzQqWK4eyJ2Z.qtL4D38thfhzkxJ1pSxSFn5fna",
"__v": 0
},
"5def2747d135311a747a9660": {
"_id": "5def2747d135311a747a9660",
"username": "dhruv1998",
"fullname": "parmar",
"email": "dhruvkp@gmail.com",
"phone": "704591556",
"password": "$2a$10$px5SK.OpP7i2Ryvg.ko/OeIbuq9XDT3luTrIBloNFCTiImUJC1BIm",
"__v": 0
}
}

如何获取所有电子邮件,例如 dhruv@gmail.com、dhruvkp@gmail.com

我尝试这样做,但没有收到电子邮件。

const userMap = {};
users.forEach(user => {
userMap[user._id] = user;
});

userMap.forEach((obj) => {
keys = Object.keys(obj);
keys.forEach((key) => {
console.log(obj[key].email);

});

最佳答案

以下代码不起作用的原因是 userMap 是一个对象(您也没有关闭外部 .forEach 循环,这将是一个语法错误):

userMap.forEach((obj) => {
keys = Object.keys(obj);
keys.forEach((key)=>{
console.log(obj[key].email);
});

为了使用.forEach(),您需要在数组(或类似数组的集合)上使用它。相反,您可以获取对象的 Object.values()Object.values() 返回一个数组,因此您可以在其上使用 .map() 来获取电子邮件属性:

const obj = {"5def224170a3ec0d90dbb89a": { "_id": "5def224170a3ec0d90dbb89a", "username": "dhruv1999", "fullname": "dhruv parmar", "email": "dhruv@gmail.com", "phone": "7045691556", "password": "$2a$10$UOk8E4fbkkZvSRSzQqWK4eyJ2Z.qtL4D38thfhzkxJ1pSxSFn5fna", "__v": 0 }, "5def2747d135311a747a9660": { "_id": "5def2747d135311a747a9660", "username": "dhruv1998", "fullname": "parmar", "email": "dhruvkp@gmail.com", "phone": "704591556", "password": "$2a$10$px5SK.OpP7i2Ryvg.ko/OeIbuq9XDT3luTrIBloNFCTiImUJC1BIm", "__v": 0 } }

const res = Object.values(obj).map(({email}) => email);
console.log(res);
console.log(res.join(', ')); // use `.join()` for string output

关于javascript - 如何访问嵌套对象中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368701/

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