javascript - 从对象数组中检索对象的数据
问题描述
我有一个这样的对象列表。
我现在被卡住了,不知道如何通过提交密钥来检索对象的值
"ListOfObjects": [
{
"SomethingToRetrieve": "This Is The First Value"
},
{
"AnotherThingToRetrieve": "This Is Another Value "
},
{
"LastToRetrieve": "This Is the Last Value"
}
]
我想通过创建一个函数:
retrieveValue(Key){
// by giving as Example AnotherThingToRetrieve
// It will return the Value of this key
//return "This Is Another Value "
}
解决方案
forEach
在您的 json 上使用。Object.keys(e)
会给你keys
内部的对象文字。
- 依次通过
JSON
- 循环遍历所有
keys
内部Object literal {}
- 如果匹配则
key
返回value
匹配。
var ListOfObjects= [{"SomethingToRetrieve": "This Is The First Value"},{"AnotherThingToRetrieve": "This Is Another Value "},{
"LastToRetrieve": "This Is the Last Value"}]
function getVal(key){
ListOfObjects.forEach(function(e){//step #1
Object.keys(e).forEach(function(eachKey){//step #2
if(key == eachKey){//step #3
console.log(e[key]);
return ;
}
})
})
// one liner using find
alert(Object.values(ListOfObjects.find(el=>Object.keys(el).find(ee=>ee==key))))
}
getVal('AnotherThingToRetrieve');
也可以使用find
方法find()
返回first element in the provided array
满足提供的测试函数的值。在 alert 下的注释语句里面。
推荐阅读
- r - 使用 dplyr 在日期之间按汇总进行分组
- amazon-web-services - 无法使用 Spotify docker 客户端启动 docker 容器
- encryption - .NET Core 5 中的 256 位加密
- html - 并排制作两个表单按钮
- swift - Swift 包管理器文件按字母顺序排列?
- python - 如何将 Microsoft Pylance 配置为不使用 django 的存根文件 (.pyi)?
- python - 带有加密链接的 Python 文件下载
- wordpress - 在电子邮件 Woocommerce 中显示可用性库存状态
- python - 如何从数据框创建 sparse_matrix?内存错误
- aggregate - Cognos Analytics 聚合多个条件