corsiKa
corsiKa

Reputation: 82559

Javascript property saying undefined

I have retrieved some data from a web service, and I am able to print the Object to the console.

data.cashiers.forEach(c => {
    console.log('c is ' + c);
    console.log('c.name is ' + c.name);
    $('#sales_entry_cashier').append(new Option(c.name, c.uid));
});

And oddly enough, it prints c entirely, but refuses to say that c.name has a value, like so:

c is {"uid":"6a661e7d-61a7-477f-b69c-f328b06819a3","name":"Admin"}      sales.js:87
c.name is undefined                                                     sales.js:88

Then, of course, it explodes when it tries to append the name and uid. How can I fix this? Clearly, in the outputted Object, there is c.name, being "Admin" - why can't I access the property?

Upvotes: 3

Views: 73

Answers (1)

javascwipt
javascwipt

Reputation: 1178

Are you sure that it is an object and not serialized?

Check the type in your response first

console.log(typeof c)

If it is a string then deserialize it

c = JSON.parse(c)

Go from there

Edit: Confirmed that it is a string.

data.cashiers.forEach(c => {
    c = JSON.parse(c)
    $('#sales_entry_cashier').append(new Option(c.name, c.uid));
});

Upvotes: 5

Related Questions