[英]Retrieving data from an object from an array of objects
我有一个像这样的对象列表。
我现在卡住了,无法弄清楚如何通过提交密钥来检索对象的值
"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 "
}
在你的 json 上使用forEach
。 Object.keys(e)
将为您提供对象文字中的keys
。
JSON
Object literal {}
所有keys
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
中满足提供的测试功能的first element in the provided array
的值。警报下的注释语句。
您可以过滤所有具有该键的对象,然后从第一个匹配对象返回值。 如果最后省略[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"))
您有一个嵌套数组。 您可以运行嵌套的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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.