What is these data structure? - javascript

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);

Related

Javascript object declaration with ternary operator

I'm declaring an object inside one of my components like below:
const data = {
user: id,
userRole: role,
teacherdepartment: department
}
But now I wanted to do this declaration dynamically depends on a specific value, like below:
let usertype='teacher';
const data = {
user: id,
userRole: role,
if(usertype=='teacher'?(teacherdepartment:tdepartment):(studentDepartment:sdepartment))
}
Is this possible. I know I can do it with nested ternary operator. But inside the object structure any simple line that can do that trick?
Update: object values can be easily set using ternary inside the object declaration, but this is for object key so this is not a duplicate of this. Also, in the above example I have put a simple object. Image if the objects have some child and ternary conditions within.
I think this could be refactored into
let usertype = 'teacher';
let departmentProperty = usertype === 'teacher' ? 'teacherdepartment' : 'studentDepartment';
let departmentValue = usertype === 'teacher' ? 'teacherdepartmentValue' : 'studentDepartment';
const data = {
user: 'id',
userRole: 'role',
[departmentProperty]: departmentValue,
};
console.log(data)
Try with conditional operator for both key and value. Keys can be made dynamic by adding [] around the key expression.
Pseude Code
const data = {
user: id,
userRole: role,
[usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
}
Working Code
const usertype = 'student';
const tdepartment = 'tdepartment';
const sdepartment = 'sdepartment';
const id = 'id';
const role = 'role';
const data = {
user: id,
userRole: role,
[usertype=='teacher'? 'teacherdepartment' : 'studentDepartment']: usertype=='teacher'? tdepartment: sdepartment,
};
console.log(data)
I'd avoid a ternary operator altogether because they're confusing to read in a lot of situations. Instead I would create a dictionary that maps user types to string values, and then create the property dynamically with that information.
const userType = 'teacher';
const dict = { teacher: 'tdepartment', student: 'sdepartment' };
const data = {
user: 'id',
userRole: 'role',
[`${userType}Department`]: dict[userType]
}
console.log(data);
While this can be done in a "one-liner" IMO to preserve readability it shouldn't be.
Instead, check usertype and create an object to include in the resulting data object. This way the changes based on usertype are isolated and easy to reason about. It also allows for additional changes based on usertype as it's isolated from the static properties.
const deptInfo = usertype === 'teacher' ? { teacherDepartment: tDepartment }
: { studentDepartment: sDepartment }
const data = {
...deptInfo,
user: id,
userRole: role,
}

How to get variable and pass value to API using JSON.stringify

I need to pass these values ​​to an API using JSON.stringify and I need to get the variables in the object.
The object that the API receives needs to look exactly like this:
{
"sessionInformation": "{\"emailAddress\" : \"the value\",\"firstName\" : \"the name\", \"question\" : \"the text\"}"
}
I'm trying this, but I'm not sure exactly how to concatenate the variables in that context
const email = some.value,
const name = some.value,
const text = some.value,
const raw = JSON.stringify({
sessionInformation:
'{"emailAddress" : email,"firstName" : name, "question" : text}',
});
How can I solve this? Thanks
You need to stringify internal object as well
const email = "Email value";
const name = "Name value";
const text = "Text value";
const raw = JSON.stringify({
sessionInformation: JSON.stringify({
emailAddress: email,
firstName: name,
question: text
}),
});
console.log(raw)

Is there any way to use array contents in object destructuring

I have an array containing elements I want to destructure it and use them as object destructuring.
I have this code in which I am destructuring keys from req.body.
const {
city,
companyName,
contactName,
contactTitle,
country,
email,
fax,
password,
phone,
role,
} = req.body;
And I want to use an array for this all data,
eg.
const temp = [
city,
companyName,
contactName,
contactTitle,
country,
email,
fax,
password,
phone,
role,
];
and use this array as keys in object destructuring
According to me:
const { [... temp ]} = req.body;
I know this is wrong but is there something I can use this array and destructure that elements from req.body.
As Rajesh mentioned in the comments, you can't do that.
Object deconstruction is some sugar syntax to help you write cleaner code in most of the use cases. In your case, since you want something kinda specific (re-use a list of attributes names), you could create your own function that would mimic the behavior you want :
function extractVars(from) {
const myVarList = [
'city',
'companyName',
'contactName',
'contactTitle',
'country',
'email',
'fax',
'password',
'phone',
'role'
];
const vars = {};
for (let v of myVarList) {
vars[v] = from[v];
}
return vars;
}
const vv = extractVars(req.body);
Assuming req.body is an object containing all the key/values, and you just want the values in the temp array, try:
const temp = Object.values(req.body)
If you also want the keys exposing as variables in the containing function's
scope, you're best to create a temp object to store them, e.g.:
let tempObj = {}
Object.keys(req.body).forEach(key => { tempObj[key] = req.body[key] })
tempObj will then contain the key/values, e,g. tempObj.city, tempObj.companyName.
Hope this helps!

How to extract an object from an array?

I have this code, where a username is required from a fake db:
const MY_FAKE_DB = require('./my_db.js')
const username = 'jdoe2';
const user = MY_FAKE_DB.users[username];
console.log(user.name, user.passwordHash)
And the "dataBase" (my_db.js) is the next one:
const users =
{
jdoe2: [{
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
}],
lmart: [{
username: "lmart",
name: "Luis",
passwordHash: "2345"
}]
}
I don´t know how to get from users the user whose username is jdoe2.
Thanks for the help
You have a few things that are causing problems here.
First to use require, you should export your object from the fake db. Something like:
// my_db.js
const users = {
jdoe2: {
username: "jdoe2",
name: "Jhoe",
passwordHash: "1234"
},
lmart: {
username: "lmart",
name: "Luis",
passwordHash: "2345"
}
}
module.exports = users // export users
Notice I changed the DB. You defined each user as an array, but that doesn' make sense and you weren't accessing them as arrays. Here each user is a single object.
Now to use it you can require it and it should work as expected:
const users = require('./my_db.js') // the exported users becomes the `users`
const username = 'jdoe2';
const user = users[username];
console.log(user.name, user.passwordHash)

Reading object property value in JavaScript object

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;

Categories

Resources