如何检查变量是否与对象数组中的键匹配,然后将键的值保存到变量中?
我有点知道该怎么办,但不确定如何写:/
const securityGroupUsers = [
{SiteSupport: "aedd8266-4015-42ea-bc1e-1325b7ee111f"},
{ServiceDesk: "b750295b-2c02-4c6b-b5cc-019b06f01650"},
{ServiceSupportTeam: "59f8e8ea-36d3-4e8c-aeee-c93823c94fb7"}
]
const variableForChecking = 'ServiceDesk';
// let valueNeeded = "b750295b-2c02-4c6b-b5cc-019b06f01650"
// TODO: Loop through securityGroupUsers to see if valueForChecking matches the key of any of the objects inside the array. If it does, then save the key value into a variable.
谢谢!
答案 0 :(得分:1)
最简单的方法是使用Array.prototype.find()
查找具有必需键的项目,而不是访问匹配项的必要属性:
const securityGroupUsers = [
{SiteSupport: "aedd8266-4015-42ea-bc1e-1325b7ee111f"},
{ServiceDesk: "b750295b-2c02-4c6b-b5cc-019b06f01650"},
{ServiceSupportTeam: "59f8e8ea-36d3-4e8c-aeee-c93823c94fb7"}
],
findItemValueByKey = (obj,keyName) => obj.find(item => keyName in item)[keyName]
console.log(findItemValueByKey(securityGroupUsers,'ServiceDesk'))