2016-03-28 149 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 
    } 
}