2

I am wondering, i have this array that has all the data I need. What I want to be able to do, is select StateCode 5 and it shows the name value Awaiting Banking Details

Here is the array layout.

var status = [
  {StateCode:1, Name:"1st Email"},
  {StateCode:2, Name:"1st Contact"},
  {StateCode:4, Name:"2nd Email"},
  {StateCode:3, Name:"Call Back"},
  {StateCode:5, Name:"Awaiting Banking Details"},
  {StateCode:6, Name:"Detail Form Emailed"},
  {StateCode:7, Name:"Refused Banking Details"},
  {StateCode:8, Name:"Signed Up Silver"},
  {StateCode:9, Name:"Welcome Letter Emailed"},
  {StateCode:10, Name:"Optimised on Web"},
  {StateCode:11, Name:"Upgraded To Gold"},
  {StateCode:12, Name:"Sent Upgrade Email"},
  {StateCode:13, Name:"Upgraded to Platinum"},
  {StateCode:14, Name:"Not Interested"}
];

3 Answers 3

2

You'll have to iterate over your objects, and check their StatusCode:

var value;
$.each(status, function(){
    if (this.StateCode == 5) {
        value = this.Name;
        return false;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Here you go:

$.each(status, function(i, value) {
   if (value.StateCode === 5) {
      alert(value.Name);
      return false;
   }
});

each will work on any object or array you pass into it. Note that it will pass two values to the callback function: the index into the collection and the value at that index.

Comments

0

If you need to do this regularly, then it's better to put this data into a better form for lookup:

var status = [
  {StateCode:1, Name:"1st Email"},
  ...
  {StateCode:13, Name:"Upgraded to Platinum"},
  {StateCode:14, Name:"Not Interested"}
];

function makeObj(array)
{
    var out = {}, i, o;
    for (i = 0; i < array.length; i++) {
        o = array[i];
        out[o.StateCode] = o.Name;
    }
    return(out);
}

var lookupState = makeObj(status);

Then, whenever you want to look up a StateCode, you can do so with this type of code:

var name = lookupState[x];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.