【问题标题】:jQuery find the match value in the multidimensional array/objectjQuery 在多维数组/对象中查找匹配值
【发布时间】:2012-09-06 10:02:57
【问题描述】:

如何正确编写此脚本,以便我可以匹配对象上的值。

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

【问题讨论】:

  • 拜托,你能更详细地描述你想要做什么吗?您的 number-property 不是对象或数组或数字。它是一个包含数字的字符串。而且您的代码中没有使用任何 jQuery?!?

标签: javascript jquery multidimensional-array


【解决方案1】:

这将返回具有包含所提供数字的数字值的对象。

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/

使用较新的 .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/

最后 - 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 2013-09-16
    • 2017-10-11
    • 2019-05-20
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多