gpt4 book ai didi

javascript - 从对象数组中的对象中检索数据

转载 作者:行者123 更新时间:2023-11-28 03:05:25 26 4
gpt4 key购买 nike

我有一个这样的对象列表。

我现在陷入困境,无法弄清楚如何通过提交 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/

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