2012-08-28 3 views
1

JSON 객체가 특정 값을 포함하고 있는지 확인하기위한 방법을 찾고 있는데, 존재하는 경우 설정을 해제하십시오.값이 들어있는 json 객체 키를 검색 한 다음 설정을 해제하십시오.

(설명과 주석)은 다음과 같이 내 데이터가 구성되어

:이 프로젝트에 밑줄 사용하고

// Search within the 'seats' array for a given 'guestID', if it exists, unset it 
tables = [ 
    { 
     "_id":{ 
     $oid: "one" 
     }, 
     "seats":[ 
     { "guestId":"01" }, 
     { "guestId":"02" }, 
     { "guestId":"03" } 
     ] 
    }, 
    { 
     "_id":{ 
     $oid: "two" 
     }, 
     "seats":[ 
     { "guestId":"11" }, 
     { "guestId":"12" }, 
     { "guestId":"13" } 
     ] 
    } 
] 

하고,하지만 난 둥지 배수로 가졌다 _.foreach 그때 _.pluck(tables, 'seats')를 사용하여 시도했다 _.foreach 구문을 사용하여 검색을 위해 좌석 배열에 액세스 할 수 있으며, 이것이 최선의 방법인지 아닌지는 잘 모르겠습니다. 내가 알지 못하는 쉬운 방법이 있습니까?

이 데이터는 mongolab REST API에서 반환됩니다. 이것은 초기 XHR 요청에서 커다란 객체를 얻은 다음 클라이언트 측에서 파싱을 시도하는 대신에해야 할 일입니까? 이것이 SQL 요청한다면 나는 과거에 이런 상황에 걸쳐 왔어요 때마다

난 그냥 select tables.seats where guestId = XXX

+0

정확히 무엇을 찾으십니까? 당신의 의견과 원하는 결과는 무엇입니까? –

+0

테이블에 원하는 좌석이있는 경우 테이블을 제거 하시겠습니까? 아니면 좌석을 제거 하시겠습니까? –

답변

1

같은 것을 할 수있을 것, 재귀 검색 기능은 항상 귀중한되었습니다 ... 여기에 내가 주위에 거짓말을했다 내 하나의 (나는 제거 방법을 추가하여 확장) :

function o (target) { 
    /// if an instance of o has been created, then handle it 
    if (this instanceof o) { 
    /// O INSTANCE: 
    /// an instance of o acts like a reference or pointer 
    /// to how the value it targets was reached. 
    this.value = target; 
    this.key = arguments[1]; 
    this.parent = arguments[2]; 
    this.toString = function(){ return 'o('+this.key+' = '+this.value+')';} 
    } 
    /// if no instance being created fall back to the 'scan object' code 
    else { 
    /// RECURSIVE CODE: 
    /// the _ function is responsible for accepting the 
    /// attributeName and attributeValue search 
    var _ = function (key, value, modifier) { 
     var i, v, tar = (modifier ? modifier.target : target), items = []; 
     /// if we are dealing with an o instance, handle slightly differently 
     if (tar instanceof o) { 
     for (i in tar.value) { 
      /// check to see if our current key and value 
      /// match our search terms 
      if (_.test(i, (v=tar.value[i]), key, value)) { 
      items.push(new o(v, i, tar)); 
      }; 
     }; 
     } 
     /// if no o instance treat as a normal object or array 
     else { 
     for (i in tar) { 
      if ((v = tar[i])) { 
      /// if we are an instance of o, recurse to actually 
      /// check the items within 
      if (v instanceof o) { 
       items = items.concat(_(key, value, {target:v})); 
      } 
      /// check to see if our current key and value match 
      /// our search terms 
      else if (_.test(i, v, key, value)) { 
       items.push(new o(v, i, tar)); 
      }; 
      }; 
     }; 
     }; 
     /// if in modifier mode, don't rely on storing in scope, 
     /// return the calculated items instead 
     if (modifier) { 
     return items; 
     } 
     else { 
     /// update what we are targeting 
     target = items; 
     /// return our underscore function 
     return _; 
     }; 
    }; 
    /// FUNCTION DECLARATIONS: 
    /// a quick test to see if the key and value match (or either or) 
    _.test = function (i,v,key,value) { 
     var havekey = (key !== null && key !== undefined), 
      haveval = (value !== null && value !== undefined), 
      passkey = (havekey && (i == key || key === '*')), 
      passval = (haveval && (v == value || value === '*')); 
     return (havekey && haveval && passkey && passval) || 
     (havekey && !haveval && passkey) || 
     (haveval && !havekey && passval); 
    }; 
    /// calculate the path needed to reach the object within the structure 
    _.path = function() { 
     var i = target.length, paths = [], path, cur, last; 
     while (i--) { 
     cur = target[i]; path = []; 
     do{ last = cur; if (cur instanceof o){ path.unshift(cur.key); } } 
      while((cur = cur.parent)); 
     paths.push(path.join('/')); 
     }; 
     return (paths.length == 1 ? paths[0] : paths); 
    }; 
    /// remove the item we are targeting by stepping back 
    /// and deleting ourselves from the previous parent 
    _.remove = function (removeEntireObject) { 
     var i = target.length, paths, path, cur, last; 
     while (i--) { 
     cur = target[i]; 
     /// remove the object that has the found attribute 
     if (removeEntireObject) { 
      if (cur.parent.parent) { 
      cur.parent.parent.value[cur.parent.key] = null; 
      delete cur.parent.parent.value[cur.parent.key]; 
      } 
     } 
     /// otherwise remove only the targeted attribute 
     else { 
      cur.parent.value[cur.key] = null; 
      delete cur.parent.value[cur.key]; 
     } 
     }; 
     return _; 
    }; 
    /// a useful function for backwards navigation 
    _.parent = function() { 
     var i = target.length, cur, items = [], values = []; 
     while (i--) { 
     cur = target[i]; 
     /// remove the object that has the found attribute 
     if (cur && cur.parent) { 
      /// store the values as we go so we can 
      /// spot and remove duplicated parents 
      if (values.indexOf(cur.parent.value) === -1) { 
      items.push(cur.parent); 
      values.push(cur.parent.value); 
      } 
     } 
     }; 
     target = items; 
     return _; 
    } 
    /// slimple debugging 
    _.alert = function() { 
     var i = target.length, cur; 
     while (i--) { 
     cur = target[i]; 
     alert(cur); 
     }; 
     return _; 
    }; 
    return _; 
    }; 
}; 

사용 예제 :

/// remove only the guestId object with a value '01' 

o(tables)('*')('seats')('*')('guestId', '01').remove(true); 

나 :

/// remove the 'guestIds' object in the first slot for either seat 

o(tables)('*')('seats')(0)('guestId', '*').parent().remove(); 

나 :

/// remove all 'guestIds' from the first seat 

o(tables)(0)('seats')('*')('guestId').parent().remove(); 

설명 : 당신은 항상 o(my_object_to_parse)를 호출하여 시작해야합니다

  • .
  • 하나의 매개 변수를 전달하면 attributeName 검색으로 작동합니다.
  • 두 매개 변수를 전달하면 attributeNameattributeValue 검색으로 작동합니다.
  • *은 기본 배열을 처리하는 데 유용한 간단한 와일드 카드 역할을합니다.
  • *attributeName 또는 attributeValue으로 사용할 수 있습니다.
  • 각 연속 요청은 구조에 한 수준 더 이동합니다.

나는 잠시 동안이 코드를 사용하지 않았으므로 100 % 버그가 없거나 최적이 아닐 수도 있습니다. 그러나 그것은 당신의 특별한 유스 케이스를 위해 작동하는 것처럼 보입니다 ... 그리고 그것은 또한 테스트하는 동안 내가 던진 모든 것을 처리했습니다. .remove(), .parent(), .path().alert()을 초과하는 더 많은 방법으로 확장하기는 쉽지만 오류 검사를 추가하는 것이 가장 좋습니다.

관련 문제