Reputation: 1583
How to check if a variable matches a key in an object array, then save the key's value into a variable?
I kinda know what to do but not sure how to write it :/
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.
Thank you!
Upvotes: 0
Views: 44
Reputation: 15530
The easiest thing you may do is to use Array.prototype.find()
to look up for an item that has required key, than access necessary property of matching item:
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'))
Upvotes: 1