Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript property saying undefined

Tags:

javascript

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?

like image 214
corsiKa Avatar asked May 13 '26 11:05

corsiKa


1 Answers

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));
});
like image 109
Uzair Ashraf Avatar answered May 15 '26 01:05

Uzair Ashraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!