2016-03-28 147 views
-5

我想訪問一個對象內的一個屬性並返回它。訪問javascript對象內的屬性

請注意對象的名稱可能會更改,因此使用title_can_change.property訪問它將不起作用。

採取下列對象:

{ 
"title_can_change":{ 
    property: 1 
} 
} 

如何退還 '財產' 的價值?

更多信息:

該對象被從含有結果從多個API的一個陣列的搜索返回。返回此對象以詳細說明結果來自的API(搜索通過多個API)。

所以這將是更喜歡:

apiData:{ 
"apiName":{ 
    price: 500 
} 
} 

「apiName」不是固定的,變化的說法API的名稱。因此,它不能由任何代碼「apiName」引用。

+0

這是「title_can_change」下具有該特定名稱的唯一屬性嗎? – StephenTG

+0

不,其他屬性可以存在,但名稱'屬性'是固定的。 –

+1

你能提供更多的細節,比如你如何改變標題,還有更多關於實際使用場景的上下文,但我可以想到的一件事是爲對象分配一個引用並使用該引用 –

回答

-6

使用for...in遍歷對象的按鍵,並檢查你的內心對象包含你的財產

var o = { 
    "title_can_change":{ 
     property: 1 
    } 
}; 

for (var k in o) { 
    if (o.hasOwnProperty(k) && o[k].property) { 
     return o[k].property; 
    } 
} 
+1

-7很酷:) – isvforall

0

如果object是全球性的,那麼你可以使用window['title_can_change']['property']。如果它是另一個對象(稱爲another_one)的另一種屬性,您可以用another_one['title_can_change']['property']訪問。

另外:你可以有一個變量(讓我們稱之爲title_name),以緩解電話:

.... 
var title_name = "title_can_change"; 
var myObj = window[title_name]['property']; 
title_name = "title_has_changed"; 
var anotherObj = window[title_name]['property']; 
..... 

OR

.... 
var title_name = "title_can_change"; 
var myObj = another_one[title_name]['property']; 
title_name = "title_has_changed"; 
var anotherObj = another_one[title_name]['property']; 
..... 
+1

但是,如果「title_can_change」更改爲「title_has_changed」,這不起作用,是嗎? – StephenTG

+0

更新了我的答案 –

0

你可以創建一個函數任何對象,你傳遞給它返回的屬性值:

var getProperty = function(obj) { 
    return obj.property; 
}; 
+0

+1,因爲這是唯一不需要嵌套對象並使用語言本身來完成工作的其他答案。 – MattSizzle

0

如果你有一個對象,你要訪問它的第一個鍵的值,你可以像去這個(骯髒的例子):

var myObj = { 
"title_can_change"{ 
    property: 1 
} 
} 

myObj[Object.keys(myObj)[0]]; 

我家這有助於。

0

所以我想我知道你在想什麼,這裏是一個低級別的解決方案,可以證明有價值的,並告訴你一些關於語言的整潔事情。

https://jsfiddle.net/s10pg3sh/1/

function CLASS(property) { 
    // Set the property on the class 
    this.property = property || null; 
} 

// Add a getter for that property to the prototype 
CLASS.prototype.getProperty = function() { 
    return this['property']; 
} 

var obj = new CLASS(9); 
alert(obj.getProperty()); 

你正在做在上面的是什麼創造了新的變量「類」。當您使用new關鍵字創建對象時,您仍然可以看到正常的JS對象(無論如何,一切都是對象),但是您可以方便地使用getProperty方法。原型上的這一點確保您創建的任何new CLASS變量都具有該方法。您可以更改變量名稱,並且通過訪問實例(變量)可以始終訪問該屬性。這是一個非常常見的面向對象的範例,是一個原型語言的優勢,所以雖然它可能超過了你的需求的頂部我想我會在這裏添加它作爲答案...

0

一種猜測,因爲問題仍然不清楚。我假設你想遍歷名字未知的對象屬性。

這可能是一個解決方案。

for (var property in object) { 
    if (object.hasOwnProperty(property)) { 
    // check objects properties for existence 
    // do whatever you want to do 
    } 
}