Obtain an object after Objects Destructuring - javascript

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.

Related

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!

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;

How to parse JSON in node js

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

Stripping unknown keys when validating with Joi

I'm using Joi to validate a JavaScript object in the server. The schema is like the following:
var schema = Joi.object().keys({
displayName: Joi.string().required(),
email: Joi.string().email(),
enabled: Joi.boolean().default(false, "Default as disabled")
}).unknown(false);
The schema above will report an error if there is an unknown key in the object, which is expected, but what I want is to strip all the unknown silently, without an error. Is it possible to be done?
You need to use the stripUnknown option if you want to strip the unknown keys from the objects that you are validating.
cf options on https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback
As in Version 14.3.4, there is a simple solution to this issue. Here is the code that solves the problem for you.
// Sample data for testing.
const user = {
fullname: "jayant malik",
email: "demo#mail.com",
password: "password111",
username: "hello",
name: "Hello"
};
// You define your schema here
const user_schema = joi
.object({
fullname: joi.string().min(4).max(30).trim(),
email: joi.string().email().required().min(10).max(50).trim(),
password: joi.string().min(6).max(20),
username: joi.string().min(5).max(20).alphanum().trim()
})
.options({ stripUnknown: true });
// You validate the object here.
const result = user_schema.validate(user);
// Here is your final result with unknown keys trimmed from object.
console.log("Object with trimmed keys: ", result.value);
const joi = require('joi');
joi.validate(object, schema, {stripUnknown:true}, callback);
Here is the current way to include the strip unknown option:
const validated = customSchema.validate(objForValidation, { stripUnknown: true });
If you pass in an objForValidation that has a key which isn't defined in your customSchema, it will remove that entry before validating.

Categories

Resources