0

I'm just beginning with JavaScript and I would like some help on a loop I need to perform. I have read many code snippets and this still seems foreign to me, and I would appreciate some guidance.

An object (car) has five properties, one of which is an array. I need to loop through the object and print each of those values. What is a good, simple way to do this--either using a single loop or a nested one? I've tried using a counter and using that value as an index number for the properties and the array, but haven't been successful. Again, I'm very new to this and so I haven't been able to relate my example to those I've read.

    var options = ["hard top", "power windows", "racing stripe", "fog 
    lights"];

    var car = {color: "red", make:"Chevrolet", model:"Camaro",  
    year:"1967", options};

    //I need a loop where with each iteration a property value of the  
    //car and an option is printed

    document.write(SOMETHING);
Alex R
  • 115
  • 3
  • Welcome to Stack Overflow! We are a question-and-answer site, not a coders-for-hire service. Please explain what you have tried so far and why it hasn't worked. See: [Why is "Can someone help me?" not an actual question?](http://meta.stackoverflow.com/q/284236) – Joe C Feb 03 '17 at 22:12
  • Also related: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) – Felix Kling Feb 03 '17 at 22:14

2 Answers2

0
Object.keys(car).forEach(function(key, idx) {
  if (key !== options) {
    console.log(car[key];
    console.log(car.options[idx]);
  }
}

This will print out on each iteration a property of the car and one of the car options which I believe was the requirement.

Object.keys(car) gives you an array of the car properties and then you iterate over each one. In this case a bit more complicated by wanting a property and an option on each loop.

rasmeister
  • 1,986
  • 1
  • 13
  • 19
0

This will loop through each key (e.g. color, make, etc.) of your car object, and print the key and the value.

Object.keys(car).forEach(key => {
  console.log(key, car[key]);
});

Will output the following:

color red
make Chevrolet
model Camaro
year 1967
options [ 'hard top', 'power windows', 'racing stripe', 'fog lights' ]
  • According to the question it says `//I need a loop where with each iteration a property value of the //car and an option is printed – rasmeister Feb 03 '17 at 22:14