I want to get first file name (Apple_Desk_1920 x 1200 widescreen.jpg
) in the array img
declared below. How do I do this?
This is my code:
var img = [{
"image" : "Apple_Desk_1920 x 1200 widescreen.jpg"
}, {
"image" : "aa.jpg"
}, {
"image" : "auroracu4.jpg"
}, {
"image" : "blue-eyes-wallpapers_22314_1920x1200.jpg"
}, {
"image" : "blue-lights-wallpapers_22286_1920x1200.jpg"
}, {
"image" : "fuchsia-wallpapers_17143_1920x1200.jpg"
}, {
"image" : "leaves.jpg"
}, ];
I want to get first file name (Apple_Desk_1920 x 1200 widescreen.jpg
) in the array img
declared below. How do I do this?
This is my code:
var img = [{
"image" : "Apple_Desk_1920 x 1200 widescreen.jpg"
}, {
"image" : "aa.jpg"
}, {
"image" : "auroracu4.jpg"
}, {
"image" : "blue-eyes-wallpapers_22314_1920x1200.jpg"
}, {
"image" : "blue-lights-wallpapers_22286_1920x1200.jpg"
}, {
"image" : "fuchsia-wallpapers_17143_1920x1200.jpg"
}, {
"image" : "leaves.jpg"
}, ];
Share
Improve this question
edited Nov 2, 2011 at 17:03
Kev
120k53 gold badges305 silver badges391 bronze badges
asked Nov 1, 2011 at 15:10
MifasMifas
251 silver badge4 bronze badges
1
-
4
How about reading some documentation about
>
arrays and>
objects? That's what documentation and tutorials are for. – Felix Kling Commented Nov 1, 2011 at 15:11
2 Answers
Reset to default 4It's:
var variableName = img[0].image;
What you have there is an array of objects. To get an array entry, you use []
with an array index (0
to one less than the length
of the array). In this case, that gives you a reference to the object. To access an object's properties, you can use literal notation as I have above (obj.image
), or using []
with a string property name (obj["image"]
). They do exactly the same thing. (In fact, the []
notation for accessing object properties is what you're using when you "index" into an array; JavaScript arrays aren't really arrays, they're just objects with a couple of special features.)
So breaking the line above down:
var variableName = // Just so I had somewhere to put it
img[0] // Get the first entry from the array
.image; // Get the "image" property from it
// dot notation
console.log(img[0].image);
or:
// square-bracket notation
console.log(img[0]['image']);
will get it for you, since you have an array of objects.