2013-11-25 3 views
-2

많은 개체가있는 배열이 존재합니다. 속성별로이 배열의 객체를 찾는 데 필요합니다.javascript의 속성을 사용하여 배열에서 객체를 찾는 방법은 무엇입니까?

입력 OBJ :

var Obj = [ 
    {"start": 0, "length": 3, "style": "text"}, 
    {"start": 4, "length": 2, "style": "operator"}, 
    {"start": 4, "length": 3, "style": "error"} 
    ]; 

출력 결과 :

var result = [ 
    {"start": 4, "length": 2, "style": "operator"}, 
    {"start": 4, "length": 3, "style": "error"} 
    ]; 
+0

잠시 시간을내어 문제를 해결하십시오. 놀랄 만한. – leaf

+0

(술 마시지 말고, 두배로 보게 ...) – leaf

+0

@wared 무엇이 잘못 되었나요? 이것은 Q & A 스타일의 작은 팁일뿐입니다. – NiLL

답변

0

_findItemByValue (값 4 "시작"을 검색) (obj가 "시작", 4);

var _findItemByValue = function(obj, prop, value) { 
    return obj.filter(function(item) { 
    return (item[prop] === value); 
    }); 
} 

IE6, IE7, IE8을 제외한 모든 버전과 호환되지만, polyfill이 존재합니다.

if (!Array.prototype.filter) { 
    Array.prototype.filter = function (fn, context) { 
    var i, 
     value, 
     result = [], 
     length; 

     if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) { 
      throw new TypeError(); 
     } 

     length = this.length; 

     for (i = 0; i < length; i++) { 
      if (this.hasOwnProperty(i)) { 
      value = this[i]; 
      if (fn.call(context, value, i, this)) { 
       result.push(value); 
      } 
      } 
     } 
    return result; 
    }; 
} 
관련 문제