1

I've a JavaScript Array like

var main = [
 { "title": "Yes", "path": "images/main_buttons/tick_yes.png"},
 { "title": "No", "path": "images/main_buttons/cross_no.png"},
]

I want to get the corresponding path value for the item which have a particular title value.

Something like

var temp = "Yes";
var result = (path value where main[0].title == temp);

I want to get the result value here.

If temp == "No", it should get me the corresponding path value.

3
  • 2
    That's not a JSON string, that's a JavaScript array (of JavaScript objects). Commented Feb 4, 2014 at 20:38
  • You'd need to loop over main and compare each elements .title value until you found the right one. Commented Feb 4, 2014 at 20:38
  • If you control the generation of this code, you could just make it an associative array, like var arr = ["yes":"someval","no","someotherval"] and access them with arr["yes"] Commented Feb 4, 2014 at 20:42

3 Answers 3

5

You can use the Array.prototype.filter method:

var result = main.filter(function(o) {
    return o.title === temp;
});

var path = result.length ? result[0].path : null;

Please note that older browsers do not the support the .filter() method. However, you can use a polyfill.

Sign up to request clarification or add additional context in comments.

Comments

1

I'd do it like this

function getPath(title, arr) {
    for (var i=arr.length;i--;) {
        if (arr[i].title == title) return arr[i].path;
    }
}

called like

getPath('Yes', main); // returns the path or undefined

FIDDLE

Comments

1

Here is one way:

var myItem = (function(arr, val){
  for(var item in arr){
    if(!arr.hasOwnProperty(item) && arr[item].title == val){
      return arr[item];
    }
  }
  return null;
})(myJSArray, "valueToMatch");

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.