JavaScript: Looping through an array of objects and filtering specific properties/attributes

Tags: , , , ,



I’m trying to loop through an array and return just the addresses and the number of packages and then having the total number of packages in the array added up. Problem is, when I write this all in codepen.io, it tells me that each name attribute is having an unexpected identifier error. I know I’ll have to work on the loop itself but what is wrong with this? Here is what I’m seeing in Codepen.io and here is the link if you want to see what codepen is showing: https://codepen.io/epbutterfield/pen/NBxMQb?editors=0012

I know it’s super simple but I must have an extra identifier or am missing one….

var deliveryItinerary = [
  {  
    name: Doctor Allen Grant,
    address: '123 Jurassic Park Trail, Kualoa Ranch, Hawaii',
    zipcode: 96744,
    packages: 5
  },
  {
    name: Harry Potter,
    address: '4 Privet Drive, Manchester, England',
    zipcode: 81726,
    packages: 8
  },
  {
    name: Bowen Knight,
    address: '1600 Camelot Court, Liverpool, England',
    zipcode: 15064,
    packages: 2
  },
  {
    name: Van Helsing,
    address: '1462 Dracula's Castle, Valerious, Transylvania',
    zipcode: 18870,
    packages: 1
  }
];

for (i = 0; i < deliveries.length; i++){
  console.log(deliveryItinerary[i].address)
  console.log(deliveryItinerary[i].packages){
    deliveryItinerary.reduce[i].packages
  }
};

Answer

Add quotes around your name values, because they’re string literals and not JS variables. Also use an extra variable, call it totalPackages, to sum up all of the packages in your loop.

const deliveryItinerary = [
  {  
    name: 'Doctor Allen Grant',
    address: '123 Jurassic Park Trail, Kualoa Ranch, Hawaii',
    zipcode: 96744,
    packages: 5
  },
  {
    name: 'Harry Potter',
    address: '4 Privet Drive, Manchester, England',
    zipcode: 81726,
    packages: 8
  },
  {
    name: 'Bowen Knight',
    address: '1600 Camelot Court, Liverpool, England',
    zipcode: 15064,
    packages: 2
  },
  {
    name: 'Van Helsing',
    address: '1462 Dracula's Castle, Valerious, Transylvania',
    zipcode: 18870,
    packages: 1
  }
];

let totalPackages = 0;
for (i = 0; i < deliveryItinerary.length; i++){
  console.log(deliveryItinerary[i].address);
  console.log(deliveryItinerary[i].packages);
  totalPackages += deliveryItinerary[i].packages;
};
console.log(totalPackages);


Source: stackoverflow