0
var stored =
        [{subject:"farm",name:"John Doe"},
         {subject:"steam",name:"Michael Buck"},
         {subject:"finance",name:"Ron Ruckle"}, //need this
         {subject:"geo",name:"Ben Bond"}];

I need to get an specific array value. I know it is possible to do this:

     getitem = stored[2]["name"];

but since I don't know the row, only the first item's value I need something like this:

     getitem = stored["subject:finance"]["name"];

2 Answers 2

2

You'd have to iterate and check:

function getNameFromSubject(subject) {
    for (var i = 0; i < stored.length; i++) {
        if (stored[i].subject == subject) return stored[i].name;
    }
    return null;
}

var name = getNameFromSubject("finance");
Sign up to request clarification or add additional context in comments.

1 Comment

Okay. I already did that with: for (var i=stored.length;i--;) { if (stored[i].subject == "finance") { return stored[i].name; } } But I thought there would be an easier&cleaner solution. Thanks for answering. Will accept your answer.
0

With modern browsers, you can use filter() to find the element you need, then get its name:

var results = stored.filter(
  function( item )
  {
    return item.subject == "finance";
  }
);

var name = results[0].name;

The MDN docs show how to add a filter() method for older browsers, as well.

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.