user6067064
user6067064

Reputation:

How to use a for loop through unknown value

I have this array shown below. Within my JavaScriptI need to console out all the customer numbers, but some of the objects the existing employees do not have a customer and therefore it is not consoling out all of the employees. Help!

I have tried doing if(!tickets[k].customernumber){console.log{"undefined")} but it still does not seem to work.

for (var k = 0; k < tickets.length; k++) {
    console.log(tickets[k].name)

[ { id: 506652,
    name: 'Sara Johns',
    age: '26',
    occupation: 'architect',
    status: 'new',
    customernumber: 26222234 },
{ id: 502452,
    name: 'Emily Johnson',
    age: '22',
    occupation: 'architect',
    status: 'existing' },
{ id: 326652,
    name: 'Claire Stevens',
    age: '23',
    occupation: 'junior architect',
    status: 'new',
    customernumber: 26222234 }

Upvotes: 0

Views: 160

Answers (2)

Harry Sun
Harry Sun

Reputation: 1

var tickets = [{
  id: 506652,
  name: 'Sara Johns',
  age: '26',
  occupation: 'architect',
  status: 'new',
  customernumber: 26222234
}, {
  id: 502452,
  name: 'Emily Johnson',
  age: '22',
  occupation: 'architect',
  status: 'existing'
}, {
  id: 326652,
  name: 'Claire Stevens',
  age: '23',
  occupation: 'junior architect',
  status: 'new',
  customernumber: 26222234
}]
for (var k = 0; k < tickets.length; k++) {
  console.log(tickets[k].customernumber ? tickets[k].customernumber : 'undefined')
}

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42460

This will print all customernumbers, skipping the records that do not have one:

tickets.filter(function(item) {
    return item.customernumber;
}).forEach(function(item) {
    console.log(item.customernumber);
});

Note that duplicate ids are currently not filtered out.

You can check MDN for more info on Array.prototype.filter() and Array.prototype.forEach().

Upvotes: 2

Related Questions