Reputation: 31590
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.
p.s. 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).
Upvotes: 0
Views: 3940
Reputation: 2565
You should use data.materials["1"].name
Jacob, I see you updated your question.
To use a variable, you simply call data.materials[your_variable_here].name
Upvotes: 2
Reputation: 11232
Did you try: data.materials[1].name
?
But in my opinion using number as property name is misleading.
Upvotes: 0