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

时间:2020-03-12 17:38:22

标签: 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 "
}

3 个答案:

答案 0 :(得分:0)

在您的json上使用forEachObject.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的值,该值满足提供的测试功能。在警报下的注释语句内。

答案 1 :(得分:0)

您可以过滤所有具有该键的对象,然后从第一个匹配的对象返回值。如果最后不使用[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"))

答案 2 :(得分:0)

您有一个嵌套数组。您可以运行一个嵌套的for循环来遍历它,直到找到这样的匹配项为止:

var listOfObjects = [
    {
        "SomethingToRetrieve": "This Is The First Value"
    },
    {
        "AnotherThingToRetrieve": "This Is Another Value "
    },
    {
        "LastToRetrieve": "This Is the Last Value"
    }
]

var key = "LastToRetrieve";
console.log(retrieveValue(key));

function retrieveValue(Key){
    // by giving as Example AnotherThingToRetrieve
    // It will return the Value of this key 
    //return "This Is Another Value "
    var value = "";
    for(var obj in listOfObjects) {
       for(var item in listOfObjects[obj]) {
          if(item === key) {
               value = listOfObjects[obj][item];
               break;
          }
       }
    }
    return value;
}