首页 > 解决方案 > 从对象数组中检索对象的数据

问题描述

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

我现在被卡住了,不知道如何通过提交密钥来检索对象的值

"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 "
}

标签: javascript

解决方案


forEach在您的 json 上使用。Object.keys(e)会给你keys内部的对象文字。

  1. 依次通过JSON
  2. 循环遍历所有keys内部Object literal {}
  3. 如果匹配则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 下的注释语句里面。


推荐阅读