Geraint
Geraint

Reputation: 3392

Propety of object is undefined

Im trying to feed in an array of objects (merchants) into a function, run through each 'merchant' and do something with the 'merchant_aw_id' of that merchant but I am getting undefined.

module.exports = function(merchants) {
  merchants.forEach(function eachMerchant(merchant) {
    console.log(merchant);
    }
  )
};

I can console.log merchant and it will return:

{ _id: 5596da54e4b05a4f29699441,
  merchant_id: '0001',
  merchant_aw_id: '6130',
  merchants: [] }

But when i do the following I get undefined:

module.exports = function(merchants) {
  merchants.forEach(function eachMerchant(merchant) {
    console.log(merchant.merchant_aw_id);
    }
  )
};

Any suggestions?

Thanks

Upvotes: 0

Views: 35

Answers (1)

Pierre
Pierre

Reputation: 19071

This is probably because the typeof merchant variable is a String which has no property merchant_aw_id.

Convert it to an object first:

module.exports = function(merchants) {
  merchants.forEach(function eachMerchant(merchant) {
    var obj = JSON.parse(merchant);
    console.log(obj.merchant_aw_id);
  });
};

Upvotes: 2

Related Questions