Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find the match value in the multidimensional array/object

How to write this script properly so I can match the value on the object.

var objGroup = [
  { "color": "YELLOW", "number": "11,7,44,22" },
  { "color": "BLUE", "number": "8,20,9" },
  { "color": "GREEN", "number": "12,34,55" }
];
objGroup.map(function (groupNum) {
  if (groupNum.number== "11") {
    alert(groupNum.color);
  } else {
    return null
  }
});​
like image 571
spicykimchi Avatar asked Feb 20 '23 04:02

spicykimchi


1 Answers

This will return the object that has a number value that contains the supplied number.

var objGroup = [
  { "color": "YELLOW", "number": "11,7,44,22" },
  { "color": "BLUE", "number": "8,20,9" },
  { "color": "GREEN", "number": "12,34,55" }
];

var found = findItem(objGroup, '11');

function findItem(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].number.split(',').indexOf(value) >= 0) {
           return objGroup[i];
        }
    }
}

if (found) {
    alert(found.color);
}

http://jsfiddle.net/rVPu5/

Alternative using newer .filter function which won't be as widely supported:

var found = objGroup.filter(function(item) {
    if (item.number.split(',').indexOf('11') >= 0) {
        return true;
    }
    return false;
});

if (found.length > 0) {
    alert(found[0].color);
}

http://jsfiddle.net/rVPu5/2/

Finally - the jQuery version:

var found = $.map(objGroup, function(item) {
    if (item.number.split(',').indexOf('11') >= 0) {
        return item;
    }
});

if (found.length > 0) {
    alert(found[0].color);
}

http://jsfiddle.net/rVPu5/3/

like image 168
Richard Dalton Avatar answered May 12 '23 12:05

Richard Dalton