我有关联的数组:
[
{
"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.我想我需要哈希,但我不知道如何:(
我该如何正确地做到这一点?
答案 0 :(得分:2)
这是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
答案 1 :(得分:1)
使用underscore:
list = [
{
"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"
}
]
query = "value 1_1"
results = _(list).filter(function(elem) {
return _(_(elem).values()).include(query)
})
console.log(results)
与原始javascript相反,此实现会考虑所有细微的细节,例如拥有/不拥有的对象属性。
答案 2 :(得分:0)
function search(arr, value) {
var ret = [];
for (var i=0, l=arr.length; i<l; i++) {
for (var k in arr[i]) {
if (arr[i][k] === value) ret.push(arr[i]);
}
}
return ret;
}