javascript - 如何找到只知道 attr 值的对象的每个属性

标签 javascript

我有关联数组:

[
    {
        "attr_1":"value 1_1",
        "attr_2":"value 2_1",
        "attr_3":"value 3_1"
    },
    {
        "attr_1":"value 2_1",
        "attr_2":"value 2_2",
        "attr_3":"value 2_3"
    },
    {
        "attr_1":"value 1_1",
        "attr_2":"value 3_2",
        "attr_3":"value 3_3"
    }
]

我需要获得完整的对象,例如,通过请求“值 1_1”。请求后我想查看对象 1 和对象 3。我想我需要哈希,但我不知道如何:(

我怎样才能正确地做到这一点?

最佳答案

这是 Array.filter 的完美案例!

yourArray.filter( function(elem) {
  // Loop attr_1, attr_2, attr_3
  for ( var i in elem ) {
    if ( elem[i] == 'value 1_1' ) {
      return true;
    }
  }
});

Array.filter 在所有浏览器中都是原生的,但在 IE8 及以下版本中不是。 在那种情况下,你必须包含这个 polyfill

/**
 * Copyright (c) Mozilla Foundation http://www.mozilla.org/
 * This code is available under the terms of the MIT License
 */
if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, this)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

更多信息: http://www.diveintojavascript.com/core-javascript-reference/the-array-object/array-filter

关于javascript - 如何找到只知道 attr 值的对象的每个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016317/

相关文章:

javascript - 如何在能够使用 API 进行搜索的同时忽略搜索中的字段?

javascript - Node JS REST API,现在如何提供 HTML 文件?

javascript - 通过在 JavaScript 中传递自定义参数来查询数据表

javascript - 按钮不会从其行中删除用户。 AngularJS

javascript - Sigma js 事件

javascript - 如何为进度条制作三 Angular 形设计

javascript - 如何检索通过 CollectionFS :S3 上传到 Amazon S3 的图像

javascript - 对具有年份和月份的字符串数组进行排序

javascript - 如果它是动态创建的,则知道选中的复选框 - Django

javascript - 背景尺寸 :cover doesn't work on iPhone 4 or 5