javascript jQuery 在多维数组/对象中查找匹配值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12404190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:06:52  来源:igfitidea点击:

jQuery find the match value in the multidimensional array/object

javascriptjquerymultidimensional-array

提问by kedomonzter

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
  }
});?

回答by Richard Dalton

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/

http://jsfiddle.net/rVPu5/

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

使用更新的 .filter 函数的替代方法,该函数不会得到广泛支持:

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/

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

Finally - the jQuery version:

最后 - jQuery 版本:

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/

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