Joseph Yi Joseph Yi - 5 months ago 9
Javascript Question

Javascript - Adding images to objects via object literal notation

I have been trying to add an image to several different objects via object literal notation.

I couldn't get it to work and was wondering if anyone had any insight on this.


Blockquote


var hotelRooms = [
{
hotel: 'Hotel Hawaii',
price: '$350 / Night',
size: '400 Square Feet',
img: 'images/image.src', // What I have tried.
image: 'images/image.src' // What I have tried.
},
{
hotel: 'Downtown Hawaii',
price: '$450 / Night',
size: '300 Square Feet',
img: 'images/image.src', // What I have tried.
image: 'images/image.src' // What I have tried.
}
];

rsp rsp
Answer

You can either add URLs:

var hotelRooms = [
    {
        hotel: 'Hotel Hawaii',
        price: '$350 / Night',
        size: '400 Square Feet',
        imgUrl: 'https://www.example.com/images/img123.jpg'
    }
];

or filenames as strings:

var hotelRooms = [
    {
        hotel: 'Hotel Hawaii',
        price: '$350 / Night',
        size: '400 Square Feet',
        imgFile: 'img123.jpg'
    }
];

or construct them from some kind of ID:

var hotelRooms = [
    {
        hotel: 'Hotel Hawaii',
        price: '$350 / Night',
        size: '400 Square Feet',
        id: 123
    }
];

by building a URL like:

"https://www.example.com/images/img" + hotelRooms[0].id + ".jpg";

When you have an URL like that - either stored directly as an object property or constructed from parts - you can use it in a template or add it to a src attribute of an <img> tag.

It's hard to say anything more because you wasn't very specific in the question on what exactly do you want to do with those images so I can only do my best in guessing.

Keep in mind that what you have here is not valid JSON. If you need to construct JSON it would be something like this:

[
    {
        "hotel": "Hotel Hawaii",
        "price": "$350 / Night",
        "size": "400 Square Feet",
        "id": 123
    }
]

with double-quoted strings and object keys.

You didn't say anything about JSON per se but people often try to process data like this as JSON and it doesn't work without properly quoted keys - those in JS it's ok to have unquoted keys (that are not reserved words) and single-quoted strings.

Comments