user68288
user68288

Reputation: 774

How can I pull a value from a JSON object from within another array?

My question title may not be the accurate way to describe this issue but it is the best I could come up with. I will make this very easy -- I am trying to get the value of VALUEIWANT from the below JSON object.

Any help would be greatly appreciated as I have been trying various methods on w3 schools for 2 hours now.

The closest I have gotten by hard coding was below:

const x =
  { "UserAttributes": 
    [ { "Name" : "sub"
      , "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
      } 
    , { "Name" : "custom:var"
      , "Value": "VALUEIWANT"
      } 
    , { "Name" : "email"
      , "Value": "[email protected]"
      } 
    ] 
  , "Username": "testuser"
  } 

const y = x.UserAttributes[1].Value
    // y here would result in VALUEIWANT

The problem with this is I am not sure that the variable will always be at index 1.

EDIT For Clarity My goal is to be able to retrieve this value of "VALUEIWANT" in my console. I need to be able to access the value by using the paired Name of "custom:var". I am unsure if this is possible.

Upvotes: 1

Views: 613

Answers (2)

kiranvj
kiranvj

Reputation: 34107

The problem with this is I am not sure that the variable will always be at index 1.

You need to find the index using findIndex (MDN)

const x = {
  "UserAttributes": [{
    "Name": "sub",
    "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
  }, {
    "Name": "email",
    "Value": "[email protected]"
  }, {
    "Name": "custom:var",
    "Value": "VALUEIWANT"
  }],
  "Username": "testuser"
}
const index = x.UserAttributes.findIndex(item => item.Name === "custom:var");

const y = x.UserAttributes[index].Value;

console.log(y);

An helper function for this would be like below

const x = {
  "UserAttributes": [{
    "Name": "sub",
    "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
  }, {
    "Name": "custom:var",
    "Value": "VALUEIWANT"
  }, {
    "Name": "email",
    "Value": "[email protected]"
  }],
  "Username": "testuser"
}

function getValue(x, name) {
  const index = x.UserAttributes.findIndex(item => item.Name === name);
  return index === -1 ? null : x.UserAttributes[index].Value;
}

// get email
console.log(getValue(x, 'email'));

// get custom:var
console.log(getValue(x, 'custom:var'))

Upvotes: 2

James
James

Reputation: 22237

Use Array.find on the x.UserAttributes array to search for the item with name of "custom:var", and take the value:

const valueYouWant = x.UserAttributes.find(ua => ua.Name === "custom:var").Value;

Upvotes: 1

Related Questions