我有关联数组:
[
{
"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/