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

标签 javascript

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

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

相关文章:

javascript - 查找数组项的最长长度 - JS

javascript - 如何使用 Protractor 在 AngularJS 中唯一识别相似元素?

javascript - 使用 cloudformation 将完整的网站部署到 AWS

javascript - Draft JS Modifier.ReplaceText 撤消/重做错误

javascript - 在javascript中将字符串变量的内容作为代码行执行?

javascript - 在 jquery 对话框中打开 jstree

javascript - JSHint:函数约定

javascript - 使用函数之外的东西的函数和自包含的函数被称为什么?

javascript - 全屏视频 HTML 5 Internet Explorer

javascript - 我的弹出窗口代码有什么问题?