I am trying to read the username property of the following JavaScript object and store it inside a variable.
[ RowDataPacket { username: 'admin', password: 'admin' } ]
It is being returned as a result object from an SQL query to a user database.
The returned object is called result
However, when I try to access its properties with
var sqlusername = result.username
or
var sqlusername = result.RowDataPacket.username
or
var sqlusername = result["username"]
or any other way to access the property,
the value of the variable var is always undefined.
How do I use the username and password properties of the object?
result is an array with one object in it. Use this:
result[0].username
Destructure the given result as
const [{ username, password }] = result;
Related
I have a javascript file with this variable. I don't understand what is the data structure. From what I read from W3Schools var x = [] is used to create an array. So what is stored in the array?
var username = $("#username").val();
var email = $("#email").val();
var password = $("#password").val();
var role = "user";
var user = [
{
username: username
},
{
email: email
},
{
password: password
},
{
role: role
}
];
It's an array of objects:
The array is designated by the square brackets [].
Inside it you have a list of objects (designated by the curly brackets with property:value pairs inside them).
var user = [ //marks the start of the array
{ //marks the start of the object
username: username //property:value pair
},
...
]//marks the end of the array
Yes - it is an array.
Rather than a data structure, you can call it an array which holds objects as its elements.
{username : username}
Look at the first element of the array. This is an object which has the property "username" in the left side. In the right side is the value of the property - which should be the current value of the variable named "username" -
This variable is defined in the first line of your code.
It is a simple object array.
Also use MDN instead of W3Schools: Array Object Working with objects
Also note that in ES6 you can store object simpler when the key has the same name as the variable
const username = "Fred";
const email = "a#b.com";
const password = "****";
const role = "user";
const user = [
{ username },
{ email },
{ password },
{ role }
];
console.log(user[1]); // email
console.log(user);
I suggest you use an object instead of an array
const username = "Fred";
const email = "a#b.com";
const password = "****";
const role = "user";
const user = {
username,
email,
password,
role
};
console.log(user.email); // much easier
console.log(user);
I have the following object:
original = {userName: "pepe", pass: "password", otherFields: "blabla"}
I want to destructure it to obtain another object with only one field: userName
If I do:
const {userName} = original
console.log(JSON.stringify(userName)) ---> "pepe", but I would like to obtain {userName: "pepe"}
Or
var newObj = {userName} = original
console.log(JSON.stringify(newObj)) ---> {userName: "pepe", pass: "password", otherFields: "blabla"}
I would like to obtain {userName: "pepe"} after running JSON.stringify(...) because it makes me easier to do a fetch with this data in the body part.
The only way that I found to do that is the following:
const _body = {}
_body.userName = original.userName
body: (JSON.stringify(_body))
But when I have more fields to send in the body, I need to add lines to this code. Is there a better way to do what I want?
Essentially when you destructure the value from the object you're getting just that...the value. So in this case userName will return the string "pepe". You'll have to pass in a new object literal into your stringify call to get the desired result:
const original = { userName: "pepe", pass: "password", otherFields: "blabla" };
const { userName } = original;
console.log(JSON.stringify({ userName }));
If you are going to eventually need more properties, you could use the rest operator to do this.
const original = {userName: "pepe", pass: "password", otherFields: "blabla"}
const {pass, otherFields, ...rest} = original
console.log(JSON.stringify(rest))
Only thing is with this route, if you have properties inside original that you may not want into the stringify, you will have to add them to the destructuring so the "rest" operator doesn't pick them up.
Let's say we have a Mongoose schema in our Node.js project:
let coolSchema = new mongoose.Schema({
field_1 : Number,
field_2 : String,
field_3 : [ String ],
});
And let's we have an according object:
var data = {
field_1 : 123,
field_2 : 'blah',
field_3 : ['aa', 'bb'],
};
Now to save this data into MongoDB we can use this code:
let Model = require('mongoose').model('CoolModel', coolSchema);
(new Model(data)).save();
Ok, while it's all cool.
But if data does not contain field_3 (array field, and the same will be for an object field) Mongoose will anyway add this field into the being created document with empty value.
Can we somehow tell Mongoose not to create this field if it's not contained in the data object?
you can do it easily skip the array field and array of object field.. This will let you skip saving empty array in new documents.but you have to use pre hook for this .
var brandSchema = new Schema({
name : {type:String},
email:String,
check:[]
})
brandSchema.pre('save', function (next) {
if (this.isNew && 0 === this.check.length) {
this.check = undefined;
}
next();
})
when new document is inserted in your schema you have to use this middlware.this works fine so try this.
this is the response when we want to insert any document
"data": {
"__v": 0,
"name": "testing",
"email": "testing#gmail.com",
"_id": "5915b018e292833edda8837f"
}
so i have send only email and name but check(array) field is skipped(Not send any value).
The accepted answer is good. But if you wouldn't want to use pre-hook, then you can add default: undefined to the array fields. For example:
var schema = new Schema({
myArr: { type: [String], default: undefined }
});
Refer to this comment for more explanation.
Not particularly an answer to the question itself but some thought on the matter.
It's not clear exactly what you're trying to achieve here. You defined a schema that is supposed to contain a list of string. Mongoose correctly does so that the data saved in your schema is consistent with the definition of the schema.
In this case, the list is more of a structural part of the schema. If you have different behaviour, you'd have to handle special case in your code in case the list isn't present. Now, you can safely assume that you schema is always returning a list so fetching some data will always allow you to do:
coolData.field_3.forEach(function(x) {
do_cool_things(x)
})
What you're asking is to make the schema allow inconsistent data being returned from mongodb... In other words, you'd have to do this in order to prevent accessing attributes on undefined:
if (coolData.field_3) {
coolData.field_3.forEach(function(x) {
do_cool_things(x)
})
}
Also, I you were trying to optimize the size of you objects/database, you could fill a bug report so mongoose doesn't define empty values while saving the objects and autofill them with defaults when the field is missing from mongodb. (I could be wrong but did you actually check if the data in mongodb was containing empty values or you were just looking at data coming from mongoose?)
It's because you're not marking the fields as required in your schema definition.
Do this:
let coolSchema = new mongoose.Schema({
field_1 : { type: Number, required: true },
field_2 : { type: String, required: true },
field_3 : { type: [ String ], required: true },
});
I want to set state to an object, so I do
const user = this.state.user;
this.setState({
user['id']: 123 //error here
});
I got unexpected token error, I also tried user.id and user[id], what's wrong?
I assume you only want to change id, but still keeping the other property of user. You can do something like this.
const user = this.state.user;
this.setState({
user: {
...this.state.user,
id: 123
}
});
Since you are anyways copying the state to a separate variable, you can just modify the object and then set it to state
const user = {...this.state.user};
user['id'] = 123
this.setState({
user
});
You way doesn't work because you cannot just directly assign a nested object a value using setState
This is not valid syntax for initializing an object. User is an object, and id is a property on that object. Use setState like this:
const user = this.state.user;
this.setState({
user: {
id: 123
}
});
See this guide for more information on working with objects in javascript.
I have this JSON array, and what I want is to get the password field alone
var user = [ { _id: 5902086ecbc0dd11e4870fd9,
password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: 'jv100#gmail.com',
lastName: 'v',
firstName: 'j',
updatedDate: 2017-04-27T15:04:14.483Z,
createdDate: 2017-04-27T15:04:14.483Z } ]
I tried to parse it using this code
var obj = JSON.parse(user);
console.log(user.password);
but still it is undefined.
User is already a list of objects, so you don't need to parse it. However, it is an array. So if you meant for it to be an array, you'd need to access the password by using this code:
console.log(user[0].password);
It's already an array there is nothing to parse. You can access your property via :
console.log(user[0].password);
You can't access your property with user.password because user variable is not object, it's an array, your object is stored at the zero index of your array.
You already have JSON object. hence, no need to parse it again.
DEMO
var user = [{ _id: "5902086ecbc0dd11e4870fd9",
password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: 'jv100#gmail.com',
lastName: 'v',
firstName: 'j',
updatedDate: "2017-04-27T15:04:14.483Z",
createdDate: "2017-04-27T15:04:14.483Z" } ];
var password = user[0].password;
console.log(password);
The variable 'user' is not a JSON array. It's an array with a single Javascript object as its element.
JSON.parse(arg) can only be used to parse a JSON string to a plain Javascript object. That being said, to access the javascript object within the array, you can do:
var userData = user[0];
To access the password within the variable, userData, you can do:
var password = userData.password;
Log the password to the console with:
console.log(password);
Try This:
var user = [ {_id:'5902086ecbc0dd11e4870fd9',password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',email: 'jv100#gmail.com',lastName: 'v',firstName: 'j',updatedDate: '2017-04-27T15:04:14.483Z',createdDate:' 2017-04-27T15:04:14.483Z' } ];
var obj = user[0];
console.log(obj.password);