같은 것을 할 수있을 것, 재귀 검색 기능은 항상 귀중한되었습니다 ... 여기에 내가 주위에 거짓말을했다 내 하나의 (나는 제거 방법을 추가하여 확장) :
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
검색으로 작동합니다.
- 두 매개 변수를 전달하면
attributeName
및 attributeValue
검색으로 작동합니다.
*
은 기본 배열을 처리하는 데 유용한 간단한 와일드 카드 역할을합니다.
*
은 attributeName
또는 attributeValue
으로 사용할 수 있습니다.
- 각 연속 요청은 구조에 한 수준 더 이동합니다.
나는 잠시 동안이 코드를 사용하지 않았으므로 100 % 버그가 없거나 최적이 아닐 수도 있습니다. 그러나 그것은 당신의 특별한 유스 케이스를 위해 작동하는 것처럼 보입니다 ... 그리고 그것은 또한 테스트하는 동안 내가 던진 모든 것을 처리했습니다. .remove()
, .parent()
, .path()
및 .alert()
을 초과하는 더 많은 방법으로 확장하기는 쉽지만 오류 검사를 추가하는 것이 가장 좋습니다.
정확히 무엇을 찾으십니까? 당신의 의견과 원하는 결과는 무엇입니까? –
테이블에 원하는 좌석이있는 경우 테이블을 제거 하시겠습니까? 아니면 좌석을 제거 하시겠습니까? –