我有一个这样的对象列表。
我现在陷入困境,无法弄清楚如何通过提交 key 来检索对象的值
"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 "
}
最佳答案
您可以过滤具有该键的所有对象,然后返回第一个匹配对象的值。如果您在末尾省略 [0]
,您将获得所有匹配值的数组。
var listOfObjects = [
{
"SomethingToRetrieve": "This Is The First Value"
},
{
"AnotherThingToRetrieve": "This Is Another Value "
},
{
"LastToRetrieve": "This Is the Last Value"
}
]
const retrieveValue = key => listOfObjects.filter(x => x[key]).map(x => x[key])[0];
console.log(retrieveValue("AnotherThingToRetrieve"))
关于javascript - 从对象数组中的对象中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60659255/