我怎样才能得到这个值?

时间:2011-10-19 21:12:47

标签: javascript jquery

假设我有一个看起来像这样的对象

var object = { id : 1, name : "Test"}

我知道在jQuery中我可以假设我有一个像这样的对象示例的数组:

$.each(arrayOfObjects, function (i, value) {
    this.id // gives me the id
    this.name //gives me the name
});

假设idname是字符串参数,我该如何获取值?

更新

我已经修改了代码,我只是想知道退出是否是一种完成此类操作的方法

var aux = 'id'
$.each(arrayOfObjects, function (i, value) {
    this.aux // gives me the id
    this+ aux
});

4 个答案:

答案 0 :(得分:2)

您以错误的方式定义了对象。 :。

要完成,请不要省略=方法的右括号。您应该已在错误控制台中注意到此错误(CTRL + SHIFT + J)。

.each

答案 1 :(得分:2)

如果我理解了这个问题,你想获得对象的键和值吗?您可以循环遍历数组中的每个对象以获取键和值。

$.each(arrayOfObjects, function() {
    // Loop though object to get its info
    $.each(this, function(i, v){
        console.log(i+': '+v); // Prints 'id: 1' and 'name: Test'
    });
});

更新:要将字符串用作对象中的键,您需要使用[]

var aux = 'id'
$.each(arrayOfObjects, function (i, value) {
    this[aux] // gives me the id
});

答案 2 :(得分:1)

value.id和value.name应包含正确的值

还要注意你应该使用'{id:1,name:“Test”}'

答案 3 :(得分:0)

将对象设置为数组,然后遍历该对象。

var object = [{ id : 1, name : "Test"}];

$.each(arrayOfObjects, function (i, obj) {
    obj.id //gives me the id
    obj.name //gives me the name
});