2014-10-11 2 views
0

이것은 매우 일반적인 질문입니다.이 질문을하기로 결정하기 전에 그 중 몇 가지를 살펴 보았습니다.이름을 모른 채 JS '객체 값 검색

objEntry: 
{ 
     objCheck: anotherObject, 
     properties: [ 
      { 
       //PropertyValue: (integer,string,double,whatever), //this won't work. 
       PropertyName: string, 
       ifDefined: function, 
       ifUndefined: function 
      } 
      ,... 
     ] 
} 

이 기능이 ... 주어진 매개 변수를 고려하여 올바르게 설계되어 무엇을하는지, 그것을 가져옵니다

은 본인은 단일 매개 변수, 다음 구문의 객체를 수신 CheckObjectConsistency라고하는 기능을 가지고 objCheck (var chk = objEntry.objCheck;)에 포함 된 다음이 컬렉션에 포함 된 properties이 있는지 확인합니다. 내가 원하는이이

for(x=0;x<=properties.length;x++){ 
    if(objCheck.hasOwnProperty(properties[x].PropertyName)){ 
     properties[x].ifDefined();    
    }  
    else{ 
     properties[x].ifUndefined(); 
    } 

처럼

... 내가 가지고 싶어 그것을 동성의 또 다른 수준 : 현재 경우, IfDefinedIfUndefined 각각 호출 할 수있는 기능이있는 제안을 감안할 때 -pointed PropertyName이 존재하고, 그렇지 않으면 매개 변수로 매우 objCheck.PropertyName의 값을 제공하면서 이러한 함수를 호출하여 사용자에게 반환하기 전에 처리 할 수있게하려고합니다.

내가 사용 예제를주지 :

나는이 기능을 내가 몇 가지 속성을 알고있는 내가 외부 공급자로부터받은 객체 (예를 들어, 외국 JSON을 반환하는-WebService에)를 공급한다

그 수도 있고 정의되지 않을 수 있습니다. 예를 들어,이 객체가 될 수 있습니다 :

var userData1 = { 
    userID : 1 
    userName: "JoffreyBaratheon", 
    cargo: "King", 
    age: 12, 
    motherID : 2, 
    //fatherID: 5,--Not defined 
    Status: Alive 
} 

또는

var userData2 = { 
    userID : 
    userName: "Gendry", 
    cargo: "Forger Apprentice", 
    //age: 35, -- Not Defined 
    //motherID: 4,-- Not Defined 
    fatherID: 3, 
    Status: Alive 
} 

내 함수가 나타납니다

var objEntry= 
{ 
     objCheck: userData1, 
     properties: [ 
      { 
       PropertyName: "age", 
       ifDefined: function(val){alert("He/she has an age defined, it's "+val+" !");}, 
       ifUndefined: function(){alert("He/she does not have an age defined, so we're assuming 20.");}, 
      }, 
      { 
       PropertyName: "fatherID", 
       ifDefined: function(val){alert("He/she has a known father, his ID is "+val+" !");}, 
       ifUndefined: function(){alert("Oh, phooey, we don't (blink!blink!) know who his father is!");}, 
      } 

     ] 
} 

CheckObjectConsistency(objEntry); // Will alert twice, saying that Joffrey's age is 12, and that his father is supposedly unknown. 

ifDefined가 실제로 대신 properties[x].ifDefined();의 경우, 나는 어떻게 든 작동합니다 properties[x].ifDefined(PropertyValue);과 함께 제공하십시오. 그리고 마침내 여기에 제 질문이 있습니다.

내면 consistency-checking-function인데, 제공된 속성의 이름 만 알고 있습니다. 내면입니다. properties[x].ifUndefined(properties[x].GetValueFromProperty(properties[x].PropertyName))과 같은 기능이 없기 때문에 단순히 값이라고 부를 수는 없지만 ... 거기 있습니까?

죄송합니다. 원어민 영어 강사가 아니기 때문에 (브라질 인), 짧은 시간에 의구심을 제대로 표현할 수 없기 때문에 긴 텍스트를 쓰는 것을 선호합니다. (잘하면 낭비되지 않은) 시도를보다 명확하게하려고합니다. .

그렇다면 내 의심이 불투명하다면 알려 주시기 바랍니다.

답변

1

여기에 대괄호 표기법이 필요하다고 생각합니다. 그것은 당신이 객체에 접근하기위한 키로서 임의의 값을 제공 할 수있게합니다. 또한 그 이름도 알고 있습니다. properties 개체를 사용하고 계십니까?

objEntry.properties.forEach(function(property){ 

    // Check if objCheck has a property with name given by PropertyName 
    if(!objEntry.objCheck.hasOwnProperty(property.PropertyName)){ 

    // If it doesn't, call isUndefined 
    property.isUndefined(); 
    } else { 

    // If it does, call isDefined and passing it the value 
    // Note the bracket notation, allowing us to provide an arbitrary key 
    // provided by a variable value to access objCheck which in this case is 
    // the value of PropertyName 
    property.isDefined(objEntry.objCheck[property.PropertyName]); 
    } 
}); 

오, 그래, forEach는 그들에 루프를 허용 배열하는 방법입니다. 그래도 일반 루프를 사용하여 동일한 작업을 수행 할 수 있습니다.

+0

Damn, D' UH!그 텍스트가 모두 우스꽝스럽게 간단한 질문으로 이어질 것이라고 나는 알아야했다. 내가 겪었던 모든 서두에서 {name : "Adam"}은 단순한 키 - 값 쌍인 것을 잊었 기 때문에 위치, 색인 또는 이름으로 연결할 수 있습니다. 재미있는 점은 몇 분 전에 답을 말씀 드리려했습니다. 첫 번째 버전입니다. 이제 추가해야합니다. 각각에 대해 잘 모릅니다 .Es는 js의 배열 객체에 유효한 메서드입니다. 처음에 코드를 보았을 때 C# 코드를 게시하고 있다고 생각했습니다. : D 감사합니다. –

관련 문제