Community
Community

Reputation: 143

JSON returning undefined values

I have a problem with a json output values returning undefined.

JSON:

[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]

CODE:

console.log(res);
res = JSON.stringify(res);
console.log(res);
var user = {};
user.user = res.user;
user.password = res.password;
user.admin = res.admin;
console.log(user);

OUTPUT:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]
[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]
{ user: undefined, password: undefined, admin: undefined }

Upvotes: 0

Views: 1626

Answers (2)

user2609980
user2609980

Reputation: 10484

The response can apparently consist of multiple items (RowDataPackets). You can get the first via index 0. And there is no need to stringify the response:

console.log(res);
var user = {};
user.user = res[0].user;
user.password = res[0].password;
user.admin = res[0].admin;
console.log(user);

Which prints

Object { user="ngx.daniel", password="Root_!$@#", admin="F"}

Upvotes: 0

Craicerjack
Craicerjack

Reputation: 6332

A few things. If this is your json:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]

you dont need to stringify it. When you stringify it you turn your object into a string. you then try to access attributes of a string, which it doesnt have.
1 - Remove the stringify
2 - Thats an array thats being returned with a RowPacketData object, which is also invalid json.
3 - To access an object in an array you need to first access the index. So it should really be something like

(if res = [ { ID: 2, user: 'ngx.daniel', password: 'Root_!$@#', admin: 'F' }])

var user = {};
user.user = res[0].user;
user.password = res[0].password;
user.admin = res[0].admin;

Upvotes: 3

Related Questions