Skip to content
Advertisement

Loop through an object by not using two for loops

I am trying to loop through an object and get the values of the properties using two for loops.

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

let carTitles=[];
for (title of fakeData.cars)
  carTitles.push(title);

for (key of fakeData.usedCars) 
  carTitles.push(key);

console.log('cars as string are:', carTitles.join(','));

I get the output as expected, but was wondering if there is a better way to do this which would prevent using two for loops. Any suggestions? (thanks for the help earlier @cybercoder)

Advertisement

Answer

You can achieve this by concatenating the arrays and using map:

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

const carTitles = [...fakeData.cars, ...fakeData.usedCars].map(car => car.title);

console.log('cars as string are:', carTitles.join(','));

If you want to keep the for ... of loop, you can also write it like this:

var fakeData = {
     "manufacturer": "tesla",
     "cars": [
          {"title": "CALI", "name": "CALI", "type": "string" },
          {"title": "TEXAS", "name": "TEXAS", "type": "string" },
          {"title": "NY", "name": "NY", "type": "string" }
     ],
     "usedCars": [
          {"title": "FL", "name": "FL", "type": "string" }
     ],
}

const allCars = [...fakeData.cars, ...fakeData.usedCars];
const carTitles = [];

for (let car of allCars) {
   carTitles.push(car.title);
}

console.log('cars as string are:', carTitles.join(','));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement