简体   繁体   中英

Javascript can't access property of an object

I have an object (returned from jQuery ajax) that looks like this:

data:{
    materials:{
        1:{
            id:1,
            name:"jacob"
        }//1 (some integer)
    }//materials
}//data

I'm trying to access name , but I can't get passed the object 1 . I tried using makeArray() like this

var m  = $.makeArray(data.materials);
var m0 = m.shift();
console.log(m);
console.log(m0);

$isArray(m) & $.isArray(m0) return true, but m and m0 both return:

1:{
    id:1,
    name:"jacob"
}//1 (some integer)

I expect that shift() to return the object that's inside of 1 .

When I try to access m0.name it returns undefined, and when I try to access m[1] it returns undefined.

btw data.materials["1"].name works. the problem is 1 is variable (I don't know what it will be, so I wanted to use shift() which doesn't work on an object).

EDIT: So it seems that there is a limitation within makeArray() : since an object property is not supposed to be named with a number, that function does not convert the rest of the object and the output is some kind of object-array hybrid (on which you cannot use array functions like shift() ), so the quick-n-dirty solution I came to was to loop thru it like this:

var m = data.materials,
    id;
for ( key in m ) { id = key; }
console.log( m[id].name );

It's not all that clean, so if there's a better way, please let me know.

ps The 1:{} is there in the first place because the controller returns multiple "materials" under certain conditions (which will never be true when this js is used).

You should use data.materials["1"].name

http://jsfiddle.net/nq4RE/

Jacob, I see you updated your question.

To use a variable, you simply call data.materials[your_variable_here].name

http://jsfiddle.net/nq4RE/1/

Did you try: data.materials[1].name ?

But in my opinion using number as property name is misleading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM