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

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)

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,
}

Json parse not convert to object

My API return user object and format is like that=>
{'id': '1', 'username': 'admin', 'image': 'https://user/testing.png', 'phno': '123'}
First I do JSON.stringify and I check the type of this line is a string.
So I use JSON.parse to get an object but its still string and can't get it likes user.id is undefined.
How can I get like user.id, user.username,...?
console.log(user);
console.log(user.user);
var test = JSON.stringify(user.user);
console.log(typeof(test));
var test1 = JSON.parse(test);
console.log(test1.id);
I think the problem might be that your API is returning JSON data with single quotation marks, and JavaScript is not able to parse it correctly. Check which JSON serializer you're using on server side. It should be like: {"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}.
This solution works for your data:
var data = '{"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}';
var user = JSON.parse(data);
console.log(user.id);
It seems like you are not getting exact user json. Issue may be backend.
const obj = `{"user":"{\\"id\\": \\"1\\", \\"username\\": \\"admin\\", \\"image\\": \\"https://user/testing.png\\", \\"phno\\": \\"123\\"}"}`
console.log(obj)
// First get value of user.
let user = JSON.parse(obj).user
console.log(typeof user) //string
// parse again, since user is string
user = JSON.parse(user)
console.log(user.username)
console.log(user.id)

What is these data structure?

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

Obtain an object after Objects Destructuring

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.

Firebase push - deletes unique object and inserts new one (Overwrites content basically)

I have an application that is running with firebase. When I try to use the push() method, it basically overwrites the existing JSON. Here's an example:
First time around, the following JSON is generated:
JSON
"deviceIDs" : {
"-JzCx5C_13eoXPEgklMW" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
Next time around, if I call the same function, the above JSON is deleted and a new JSON is inserted such as this one:
JSON
"deviceIDs" : {
"-JzCxbuEj2V1kmvvgqnc" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
Here's my code snippet:
function CreateUserProfile(UID, name, email, deviceID) {
var ref = new Firebase($scope.firebaseurl + '/' + UID);
var profileArray = {UserProfile:{}};
profileArray.UserProfile.UID = UID;
profileArray.UserProfile.name = name;
profileArray.UserProfile.email = email;
profileArray.UserProfile.deviceID = deviceID;
var onComplete = function (error) {
if (error) {
console.log('Synchronization failed');
} else {
//1. On Success, Store Key User Profile Elements
localStorage.setItem("kasimaProfileInfo",JSON.stringify(profileArray));
$rootScope.username = name;
//2. Hide the feedback and change screens
$timeout(function () {
$scope.HideFeedback();
$scope.ChangeLoc('/featured');
}, 1500);
}
};
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
var newPostRef = postsRef.push();
newPostRef.set({
deviceID: deviceID,
author: "gracehop22",
title: "Announcing COBOL, a New Programming Language"
});
}
You're overwriting the entire ref when you're setting profileArray:
...
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
You'll probably want to use update() there:
...
ref.update(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
Update
The Firebase update() functions set the value of the properties in the JSON object you pass it. So your new profileArray.UserProfile will replace the existing data.
The solution is to not build a nested JSON structure locally, but instead update the data at the lower location where it needs updating:
ref.child('UserProfile').update(profileArray.UserProfile, onComplete);
This removes the entire need for the profileArray:
var userProfile = {
UID: UID,
name: name,
email: email,
decideID: deviceID
};
ref.child('UserProfile').update(userProfile, onComplete);
For a working example, see: http://jsbin.com/ciqoge/edit?js,console
For a next time: if you provide such a jsbin/jsfiddle straight away, it will be much easier to quickly help you.

Categories

Resources