I have a multidimensional object (it's basically an array):

Object = { 1 : { name : bob , dinner : pizza }, 2 : { name : john , dinner : sushi }, 3 : { name : larry, dinner : hummus } }

I want to be able to search the object/array for where the key is "dinner", and see if it matches "sushi".

I know jQuery has $.inArray, but it doesn't seem to work on multidimensional arrays. Or maybe I'm wrong. indexOf also seems to only work on one array level.

Is there no function or existing code for this?

share|improve this question
This has been asked before. You have to write your own function or use some other library. – Felix Kling Mar 3 '11 at 13:47
Please note that Object is reserved in Javascript, Object is the object object, ie the mother of all objects. – adamse Mar 3 '11 at 14:15
feedback

2 Answers

up vote 25 down vote accepted

If you have an object like this

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

Ignore what's below. Use the filter method!

peoples.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

You can search for people who have "dinner": "sushi" using a map

peoples.map(function (person) {
  if (person.dinner == "sushi") {
    return person
  } else {
    return null
  }
}); // => [null, { "name": "john", "dinner": "sushi" }, null]

or a reduce

peoples.reduce(function (sushiPeople, person) {
  if (person.dinner == "sushi") {
    return sushiPeople.concat(person);
  } else {
    return sushiPeople
  }
}, []); // => [{ "name": "john", "dinner": "sushi" }]

I'm sure you are able to generalize this to arbitrary keys and values!

share|improve this answer
1  
Just keep in mind that these solutions are part of ECMAScript 5 and not supported in IE8. kangax.github.com/es5-compat-table As much as I prefer @adamse's answer, alex's is more "old shitty browser" friendly. Not sure about performance though. – EasyCo Sep 25 '12 at 5:46
@SalmanA - nor the question or the solution is referring to jQuery. The javascript filter() is used, not jQuery-specific $.filter() - tutorialspoint.com/javascript/array_filter.htm – Tapirboy Jan 14 at 14:14
feedback
var getKeyByDinner = function(obj, dinner) {
    var returnKey = -1;

    $.each(obj, function(key, info) {
        if (info.dinner == dinner) {
           returnKey = key;
           return false; 
        };   
    });

    return returnKey;       

}

jsFiddle.

So long as -1 isn't ever a valid key.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.