Another form of Object literals in JSON? - javascript

I'm trying to figure out how to make this work:
var emails = $("#register_Email").val();
var split = emails.split("#");
var username = split[0];
var first = $("#register_FirstName").val();
var last = $("#register_LastName").val();
var phone = $("#register_PhoneNumber").val();
ref2.set({
username: {
active: true,
email: emails,
first_name: first,
last_name: last,
phone: phone,
role: "technician"
}
});
I can get all of the variables but the problem is I want to pass it into the set() method as seen above. The name of the whole node should be the value of the username, not the word username.
I've tried using literals in this way:
ref2.set({
[username]: {
active: true,
email: emails,
first_name: first,
last_name: last,
phone: phone,
role: "technician"
}
});
But that doesn't work. It just crashes saying I can't pass [ or ] as variable names.

Can't do it with object literal. But you can remember that foo.bar is equivalent to foo['bar'], and write this instead:
var opts = {};
opts[username] = {
active: true,
email: emails,
first_name: first,
last_name: last,
phone: phone,
role: "technician"
};
ref2.set(opts);

Related

JavaScript object shorthands

I have this clunky code here and hope there is any way to shorten this.
By the way, "req.query" is my query object from an nodejs express server.
const q = req.query
User.insertOne({
firstName: q.firstName,
lastName: q.lastName,
bestFriend: q.bestFriend,
hobbies: q.hobbies,
address: {
street: q.address.street,
number: q.address.number,
plz: q.address.plz,
city: q.address.city,
country: q.address.country,
},
contact: {
telephone: q.contact.telephone,
email: q.contact.email,
},
})
My first solution was - as you can see - to replace req.query with q, but this does not seem to be enough.
Maybe you could do this with the "with" statement, but i haven't used it before and I've heard that you shouldn't implement it (don't know why....).
By reading your title I understood you want to use ES6 object property shorthand. To achieve that in your current setup you would also need to use object destructuring, here's the code:
//Object destructuring:
const { firstName, lastName, bestFriend, hobbies } = req.query;
const { street, number, plz, city, country } = req.query.address;
const { telephone, email } = req.query.contact;
//Using the ES6 object property shorthand:
User.insertOne({
firstName,
lastName,
bestFriend,
hobbies,
address: {
street,
number,
plz,
city,
country,
},
contact: {
telephone,
email,
},
})
As long as the property names matches with each other, you can directly assign them in javascript and the relevant properties will be mapped.
const q = req.query
User.insertOne(q);
If the properties don't match, use spread operator ( ... ) from ES6 which comes handy while mapping objects.
You can use the lodash library and use a the pick method.You only need to specify the names of the fields that you want from req.query,and it'll return an object containing those values which you can use.
const _ = require("lodash");
User.insertOne(_.pick(req.query, [
"firstName",
"lastName",
"bestFriend",
"hobbies",
"address.street",
"address.number",
"address.plz",
"address.city",
"address.country",
"contact.telephone",
"contact.email"
]))
In case the OP's task was about passing just a subset of the queried data into the method (but actually not just for that) then the OP might have a look into the destructuring assignment syntax, into the spread syntax as well as into the rest parameters syntax.
const req = {
query: {
foo: 'Foo',
bar: 'Bar',
firstName: 'Anni',
lastName: 'Smith',
bestFriend: 'Jane Doe',
hobbies: '',
address: {
street: 'Any Lane',
number: 42,
plz: '1-234-456',
city: 'Some City',
country: 'Motherland',
},
contact: {
telephone: '9-87-654-321',
email: 'anni.smith#provider.com',
},
more_not_needed_data: {
baz: 'Baz',
biz: 'Biz',
},
},
};
const userDataFromRest =
(({ foo, bar, more_not_needed_data, ...data }) => data)(req.query);
const explicitUserData = (
({
firstName, lastName, bestFriend, hobbies, address, contact,
}) => ({
firstName, lastName, bestFriend, hobbies, address, contact,
})
)(req.query);
/*
User
.insertOne((({ foo, bar, 'more not needed data', ...data }) => data)(req.query));
User
.insertOne((
({
firstName, lastName, bestFriend, hobbies, address, contact,
}) => ({
firstName, lastName, bestFriend, hobbies, address, contact,
})
)(req.query));
*/
console.log({
query: req.query,
userDataFromRest,
explicitUserData,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

How can I take a values of one object and put them into another object

Hey guys I have the following setback, I am trying to write on empty values of an object already filled another value so I can use them later, I have defined the object and I am trying to reassign the values with the new one after I receive them from API call, the problem is that the object that I am receiving is the same as the one from the API call and I don't need that, I am in need of the same structure that I have created, for this to happen I am using useState. Could you point me in the right direction?
That is my code and after it will be the result I am always getting
The initial state of deliveryAddressInput before API call
const [deliveryAddressInput, setDeliveryAddressInput] = useState<NewAddressDetails>({});
The result after the call of the API is setDeliveryAddressInput(adress):
BuildingName: "18A"
BuildingNumber: ""
City: "Houghton Le Spring"
Line1: "18A Nesham Place"
Line2: ""
Line3: ""
PostalCode: "DH5 8AG"
Initial state of the mapped object from the top one:
const [newAddress, setNewAddress] = useState<{}>({
firstName: firstNameInput,
lastName: lastNameInput,
houseNo: deliveryAddressInput.BuildingNumber,
houseName: deliveryAddressInput.BuildingName,
street: deliveryAddressInput.Line1,
addressLine2: deliveryAddressInput.Line2,
town: deliveryAddressInput.City,
postCode: deliveryAddressInput.PostalCode,
});
The useState function:
useEffect(() => {
setTimeout(() => {
setNewAddress(deliveryAddressInput);
});
}, [deliveryAddressInput]);
And the final result is the same as the call from the API:
BuildingName: "18A"
BuildingNumber: ""
City: "Houghton Le Spring"
Line1: "18A Nesham Place"
Line2: ""
Line3: ""
PostalCode: "DH5 8AG"
I am trying to receive the following which is mapping the values of the API call to the new object keys:
firstName: "Jane",
lastName: "Smith",
houseNo: "",
houseName: "18A",
street: 18A Nesham Place,
addressLine2: "",
town: "Houghton Le Spring",
postCode: "DH5 8AG",
I suppose you should convert one object into another:
const convertDeliveryInputIntoAddress = (
deliveryAddressInput, firstName, lastName
) => {
const {BuildingName, BuildingNumber, City, Line1, PostalCode} = deliveryAddressInput;
const firstLineSplitted = Line1.split(' ');
const houseName = firstLineSplitted[0];
const street = firstLineSplitted.slice(1).join(' ');
return {firstName, lastName, houseNo: buildingNumber, houseName, street, town: City, postCode: PostalCode};
}
...
setNewAddress(convertDeliveryInputIntoAddress(deliveryAddressInput, firstName, lastName));

Convert Array with objects to manipulate

I'm trying to manipulate this array and play with parse, push and save data commands. but for some reason is not reading.
Any help?
I'm super new to it and just trying to practice.
Should be an array of objects.
var employeeString = [
{ first_name: 'Josh', last_name:'Neil', nationality:'Indian'},
{ first_name: 'Brian', last_name:'Cok', nationality:'Canadian'},
{ first_name: 'Katja', last_name:'Fanta', nationality:'German'}
];
var jsonValues = JSON.stringify(employeeString);
current_values = JSON.parse(jsonValues);
var nationality = [];
//console.log (current_values);
for ( i = 0; i < current_values.length; i++) {
var currentItem = current_values[i]
var first_name = currentItem['first_name'];
var last_name = currentItem['last_name'];
//push value into array
nationality.push(currentItem['nationality']);
if (currentItem == 'first_name' || currentItem == 'last_name') {
return id[i+1];
}
}
console.log (first_name , last_name);
You don't need to parse the already JSON object.
For example JSON.parse('[{x:10},{y:20}]'); will return JSON object from the string. This step is required to access the value of x and y, which are in string form as you can see '' around it. But in your case, you already got a JSON Object you don't need to parse it again.
Further in console.log if you want to print first_name, do not add '' around it. Here is your working code
var current_values = [
{ first_name: 'Josh', last_name: 'Neil', Nationality: 'Indian' },
{ first_name: 'Brian', last_name: 'Cok', Nationality: 'Canadian' },
{ first_name: 'Katja', last_name: 'Fanta', Nationality: 'German' }
];
// current_values = JSON.parse(employeeString);
// console.log(current_values);
for (i = 0; i < current_values.length; i++) {
var currentItem = current_values[i]
var first_name = currentItem['first_name'];
var last_name = currentItem['last_name'];
console.log(first_name, last_name);
}
The JSON.parse method accepts a string, but you're giving it an array of objects.
var values = JSON.parse("[{'first_name': 'Josh', ...}, ...]");
Would work better.
In general, parsing will convert a string to objects. http://www.willamette.edu/~fruehr/haskell/seuss.html
The data type for employeeString is Array, but JSON.parse() is supposed to parse JSON data. So, you can first change employeeString into a JSON data before parse it.
You don't need to JSON.parse(employeeString), since it is already an object.
JSON.parse is used to create objects from their string representation, e.g. parse the string '{"prop":42}' to an actual object with a property prop and its value being 42. Since employeeString in your code is already an object, you don't need to JSON.parse it again.
BTW, you probably meant this:
// notice that this is now an actual string
var employeeString = `[
{ first_name: 'Josh', last_name:'Neil', Nationality:'Indian'},
{ first_name: 'Brian', last_name:'Cok', Nationality:'Canadian'},
{ first_name: 'Katja', last_name:'Fanta', Nationality:'German'}
]`;

printing the data of objects by storing it in variables

I have an object named data and on console of data, I did :
var data={
countrycode: "376",
dob: "2017-05-24",
email: "bsbsbs#gmail.com",
firstName: "ggsgsggsg",
gender: "male",
phoneNumbers: "88888888888888888",
surName: "hshshhshs"
}
let countrycode,iso2,number,firstName,surName,dob,gender,email;
countrycode=data.countrycode;
number=data.phoneNumbers;
firstName=data.firstName;
surName=data.surName;
email:data.email;
gender:data.gender;
dob:data.dob;
console.log('email is',email);
console.log('number is ',number);
console.log('gender is',gender);
console.log('surName is',surName);
console.log('dob is',dob);
console.log('firstName is',firstName);
What I see that as i console log the values , i get undefined for email,gender and dob and for rest of the others , i get the correct values .
What can be the reason this and why does this happen ?
You have to actually use = as an assignment operator in the example you gave, colons are for object property assignment.
email = data.email;
gender = data.gender;
dob = data.dob;
Use = for assignment, not : (which is reserved for assigning values to an Object's property).
It would be
email=data.email;
Not
email:data.email;
var data={
countrycode: "376",
dob: "2017-05-24",
email: "bsbsbs#gmail.com",
firstName: "ggsgsggsg",
gender: "male",
phoneNumbers: "88888888888888888",
surName: "hshshhshs"
}
let countrycode,iso2,number,firstName,surName,dob,gender,email;
countrycode=data.countrycode;
number=data.phoneNumbers;
firstName=data.firstName;
surName=data.surName;
email=data.email;
gender=data.gender;
dob=data.dob;
console.log('email is ',email);
console.log('number is ',number);
console.log('gender is ',gender);
console.log('surName is ',surName);
console.log('dob is ',dob);
console.log('firstName is ',firstName);

If statement syntax error in JS

I am trying to use an if/else and I can't figure out where I'm going wrong with the syntax. I want the payload to only submit school_ids if the role isn't p_admin. Thank you for your help!
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
if (role !== 'p_admin'){
school_ids: payload.schoolIds
}
})
);
I see 2-3 options depending on your excludeObjNullValue function:
You can either break that expression up in to a couple of statements, or
Or use property spread notation and the conditional operator, or
If excludeObjNullValue does what the name suggests, you can use a conditional without spread notation and rely on excludeObjNullValue to exclude it
Option 3 may well be your best bet, but I'll give them in order:
Option 1: The multi-statement way:
const createUser = (payload) => {
const options = {
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
};
if (role !== 'p_admin') {
options.school_ids = payload.schoolIds;
}
return request.postJSON('/register', excludeObjNullValue(options));
};
Option 2: Property spread and the conditional operator
Property spread is a Stage 3 proposal but support for it is already shipping in Chrome and Firefox, and if you're transpiling you can tell your transpiler to support it. That would look like this:
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
{...(role !== 'p_admin' ? {school_ids: payload.schoolIds} : {}}
}
})
);
Whether it's a good idea even if supported is your call. :-) It does briefly create an extra object and iterator.
Option 3: Rely on excludeObjNullValue to exclude properties with null values:
If it really does what the name suggests, then it will remove school_ids if we give the value null to it. So:
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
school_ids: role !== 'p_admin' ? payload.schoolIds : null
}
})
);
You can't write if statement at the object declaration. Also you need to explicitly defined body for your arrow function. So you can do something like
const createUser = (payload) => {
const obj = {
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId
};
if(obj.role !== 'p_admin') {
obj.school_ids = payload.schoolIds
}
return request.postJSON('/register', excludeObjNullValue(obj));
}

Categories