2012-11-12 6 views
-1

mongodb 및 ajax 호출을 사용하여 데이터를 검색하고 있습니다. 자바 스크립트 객체로 바뀌면 때때로 HTML을 생성하는 데 사용하는 속성이 존재하지 않습니다. 이 호출에 봐 :N 레벨에서 객체 속성 호출하기 자바 스크립트

$.ajax({ 
     url: 'api/v1/mention/'+id, 
     type: "GET", 
     dataType: "json", 
     data : {login : "demo"}, 
     success: function(mention) { 
      display_mention_text(mention.texto); 
     } 
    }); 
내가 mention.texto를 호출하고있어이 경우

하지만 mention.picture 수 또는 속성. 때로는 정의되지 않았으며 앱이 다운됩니다.

이 메서드는 개체에서 속성을 호출하고 정의되지 않은 경우 빈 문자열을 반환합니다. 이 메소드를 호출하는 몇 가지 예는 (첫 번째 개체이고, 다른 하나는 재산) 다음 경우, 첫 번째 방법의 get_property에서

function get_property(obj){ 
    var args = Array.prototype.slice.call(arguments), 
    obj = args.shift(); 
    if (checkNested(obj,args)) { 
     //what should I do here? 
    } else{ 
        //the property is undefined and returns "" 
     ""; 
    }; 
} 


    //check if a object has N levels of propertys 
function checkNested(obj /*, level1, level2, ... levelN*/) { 
    var args = Array.prototype.slice.call(arguments), 
     obj = args.shift(); 

    for (var i = 0; i < args.length; i++) { 
    if (!obj.hasOwnProperty(args[i])) { 
     return false; 
    } 
    obj = obj[args[i]]; 
    } 
    return true; 
} 

:

방법과 같이 정의된다
get_property(mention,"text") 
get_property(mention,"user","name") 
get_property(mention,"picture") 

아래와 속성은 존재합니까, 어떻게 부르세요 ?? 나는 객체와 배열이 같은 자신의 propertys 것 : 객체

params = ["user","name"] 

을하지만, 나는 다음과 같이 호출 할 수 없습니다 : 필요 (

object.["user","name"] 
+0

'get_property' 함수의'if' 문을'checkNested' 함수의'for' 루프로 대체하십시오. 그런 다음'true' 또는'false'를 리턴하는 대신 찾은 값 또는'' "를 리턴하십시오. –

+0

하지만 checkNested 함수는 값이 아니라 true 또는 false를 반환합니다. –

+0

내가 설명했던 것을 수행하는 [답변] (http://stackoverflow.com/a/13345966/1689607). 그러나 다시, 당신은 * if 문 전체를 대체하고 다른 함수로부터'for' 문을 그 자리에 놓습니다. 그런 다음 * 반환 값을 변경하여 더 이상 true 또는 false를 반환하지 않습니다. –

답변

2

가있는 if 문을 바꾸기 : 당신이 정의되지 않은 속성을 기대하는 경우

obj['user']['name']; 

(정말, 그 다른 뭔가 문제가 있다는 뜻) : 당신이 당신의 객체의 트리를 알고, 그냥 전화 get_property 함수는 checkNested 함수에서 for 루프를 사용합니다. 그런 다음 true 또는 false을 반환하는 대신 발견 된 값 또는 ""을 반환하십시오.

function get_property(obj){ 
    var args = Array.prototype.slice.call(arguments), 
     obj = args.shift(); 

    // Here's your 'for' loop. The 'if' statement is gone. 
    for (var i = 0; i < args.length; i++) { 
     if (!obj.hasOwnProperty(args[i])) { 
      return ""; // I changed the value of this 'return' statement 
     } 
     obj = obj[args[i]]; 
    } 
    return obj; // I change the value of this 'return' statement 
} 

다시 말하지만, 모든 I 한 사본이 다른 하나의 함수에서 자신의 코드를 붙여 및 return 문장의 값을 변경했다.

+0

이 코드는 매우 멋지다. 나는 다른 방법을 잊어 버린 새로운 방법에 너무 집중했다. –

1

당신은이 방법으로 목표를 달성 할 수 checkNested의 기능) :

//Parameters {obj, prop1, prop2, ... propN} 
function get_property(){ 
    var args = Array.prototype.slice.call(arguments), 
     obj = args.shift(), 
     prop = args.shift(); 

    if(obj.hasOwnProperty(prop)){ 
     if(args.length > 0){ 
      //Calling 'get_property' with {obj[prop1], prop2, ... propN} , and so on 
      return get_property.apply(get_property, [obj[prop]].concat(args)); 
     }else{ 
      return obj[prop]; 
     } 
    }else{ 
     return ""; 
    } 
}​ 

사용법 :

var o = { 
    "a" : { 
     "b" : 5 
    } 
}; 

console.log(get_property(o,"c"));  // "" 
console.log(get_property(o,"a","b")); // 5 
console.log(get_property(o,"a"));  // {"b":5} 
0

당신은 단순한 재귀 함수를 찾고 있습니다.

function get_property(obj, prop) { 
    if (obj[prop]) { 
     return obj[prop]; 
    } 
    else { 
     var end; 
     for (var p in obj) { 
      if (obj.hasOwnProperty(p)) { 
       end = get_property(obj[p], prop); 
      } 
     } 
     if (!end) { 
      // If we're there, it means there's no property in any nested level 
      return; 
     } 
     else { 
      return end; 
     } 
    } 
} 

편집 : 질문이 잘못되었습니다. 대신 @ Engineer 's answer를 참조하십시오. 누군가가 이런 식으로 보이는 경우에 대비하여이 답변을 유지하십시오.

0

너무 복잡합니다.

var prop; 
try { 
    prop = obj.user.name; 
} 
catch (e) { 
    prop = null; 
} 
+0

실제로이 경우에는 가독성을 위해'obj.user.name'을 사용하는 것이 좋습니다. – ThiefMaster

+0

@ThiefMaster, 그에게 어울리는 것이 무엇이든간에. –

+0

개체의 세 가지를 알고 있지만 개체 사용자의 속성 이름은 정의되지 않았을 수 있습니다. 그렇다면 obj [ 'user'] [ 'name']는 예외를 발생시킵니다. –