1

I am trying to select an object from this array and print all of its properties into an element, using "data-id". How would I go about doing this? Also, how can I give an ID to the new CarObjects?

**<div id="carInfo" data-id="10"></div>**

function Car(company, name, price, details, image, alt){ 
    this.company = company;
    this.name = name;
    this.price = price;
    this.details = details;
    this.image = image;
    this.alt = alt;
}

var carInformation = [new Car("Ferrari", "Marenello", " $250,000", "Fast. Very Fast.", "images/ferrari.jpg","image of ferrari"),
                      new Car("Dodge", "Viper", " $100,000","Great Acceleration","images/dodge.jpg", "image of viper"),
                      new Car("Ford", "Shelby", "$80,000", "Muscle Car", "images/mustang.jpg", "image of mustang"),
                      new Car("Back To The Future", "Delorean", "$20,000", "Travels through time","images/delorean.jpg", "image of delorean"),
                      new Car("Lamborghini", "Diablo", "$250,000", "Fastest","images/lambo.jpg","image of lamborghini"),
                      new Car("CMercedes Benz", "SLR", "$180,000", "Classy Vehicle.","images/benz.jpg","image of mercedes benz"),
                      new Car("Chevrolet", "Corvette", "$70,000", "Fiberglass body Light Vehicle.","images/vette.jpg","image of corvette"),
                      new Car("Porsche", "Carrera", "$120,000", "Great Handling.","images/porsche.jpg", "image of porsche"),
                      new Car("Audi", "R8", "Price: $110,000", "Fast and Classy.", "images/audi.jpg","image of audi") ];
DrZoidberg
  • 23
  • 5

1 Answers1

3

jQuery lets you get the data-id attribute via the data() method;

var carInfo = carInformation[$('#carInfo').data('id')];

Object.keys(carInfo).forEach(function (val) {
    console.log(val + " is " + this[val]);
}, carInfo);

The above snippet uses code from the ECMAScript5 specification, which is not supported in older browsers. If you wish to support them, you need to make use of a ES5 shim or polyfiller, or use the snippet below:

var carInfo = carInformation[$('#carInfo').data('id')];

for (var x in carInfo) {
    if (carInfo.hasOwnProperty(x)) {
        console.log(x + " is " + carInfo[x]);
    }
}

Printing it into an element depends on how you want it formatted, but the above code will give you all the details you should need to be able to do this.

EDIT: Bear in mind that your carInformation array only has 8 elements in it...

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180