I am trying to make sense of this line of code:
const loanPeriod: number = get(product, 'TermMonths', this.defaultTerm) / this.monthsInAYear;
defaultTerm and monthsInAYear are global variables. product is an object and TermMonths is a number property of product. I don't know why the product & 'TermMonths' is needed. Can't you just divide the defaultTerm by monthsInAYear?
You can find the official documentation here, with an example. Using your case, the assumption is that product may or may not have a property called TermMonths. If it does, _.get will retrieve the value of that property. If it does not, the default, this.defaultTerm, is returned.
The _.get() method is used to get the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
Syntax:
_.get(object, path, [defaultValue])
Parameters: This method accepts three parameters as mentioned above and described below:
object: This parameter holds the object to query.
path: This parameter holds the path of the property to get. The path will be array or string.
defaultValue: This parameter holds the value returned for undefined resolved values.
Return Value: This method returns the resolved value.
src: https://www.geeksforgeeks.org/lodash-_-get-method/
In your case it gets the term of loan if not it takes default and divides it by months in years to get the total years.
Related
The document in the target collection ("myCollection") has a field called "japanese2". This is an array (or an object) that contains an object that contains a property called "japanese2a". The value of this property is initially set to 0 (although it may change later). I want to change this value to 100 with a script in node.js (I am using the Express framework). The database is Mongodb, the free cloud version called Atlas.
If I do this without using variables, it works well:
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{"japanese2.0.japanese2a":100}});
However, if I try this using variables for both the field name, "japanese2", and the name of the element/property in the array/object, "japanese2a", it fails. I have tried the below and other variations but I couldn't find a solution. I have researched stackoverflow for an answer but couldn't find a solution.
There is only one element/property in the array/object to start with.
var field = req.body.fieldName; //want to set this for the field name="japanese2"
var task = req.body.question; //want to set this for the name of the element="japanese2a"
var myField = [task];
field = myField;
var fieldPos = field[0];
.
.
.
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{[fieldPos]:100}});
The above creates a new field called "japanese2a":100" but it does not appear in the array under the field called "japanese2", which is what I want.
I don't get any error messages when I do the above in the console (probably mostly due to the fact that I haven't put in error statements/functions to catch errors), but the output is not correct.
Another way of updating that I found from here:
https://www.codementor.io/#prasadsaya/working-with-arrays-in-mongodb-16s303gkd3
that involves using something like this:
db.posts.updateOne(
{ _id : ObjectId("5ec55af811ac5e2e2aafb2b9"), "comments.user": "Database Rebel" },
{ $set: { "comments.$.text": NEW_CONTENT } }
)
doesn't work for me, as I don't know if the initial value of the element in the array will always be a zero or some other constant. And there is only one element in the array initially. I can only use the username for the match part in the updating. I can't make an expression that is a perfect match for some element in the array.
The update solution from here: MongoDB update data in nested field
db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });
works, and that is what I used successfully to update in the first updating attempt above, but I don't know how to incorporate variables into the updating operation, specifically a variable for the field name ("japanese2") that holds the array or the object, and the name of the first and only element/property in the array/object ("japanese2a").
EDITED: I asked for a solution for an "array" originally, but either a field that acts an array (that holds elements that act as objects) or an object (that holds other objects as properties) works in my case, so I edited the question body and title. Also, the accepted solution works with the field as an entity that holds an array, or as an entity that contains an object inside it.
In either case, if there is already a field with the appropriate name, an object is created (if it didn't already exist) as an object of that object called "field" or the array called "field", and the object's property is set as according to the variables in the script.
If the field doesn't exist, it's created (as an object), and this object contains another object that contains the property ("task" as the name and "100" as the value for the name-value pair). So the newly created "field" object contains an object as its property. The property of this object is a name-value pair of "japanese2a" and "100".
If the script is run again, with a different "task" name (eg. "japanese2b"), another property is created, with the name of "japanese2b" and the value of "100". It is created within that same object that is "inside" the "field" object, so the object field.0 (the object within the "field" object) ends up looking like this: {japanese2a: 100, japanese2b: 100}. And the object called "field" looks like this: {{japanese2a: 100, japanese2b: 100}}.
I think something like
var field = req.body.fieldName // japanese2
var task = req.body.question; // japanese2a
var updateObj = { $set : {} };
updateObj.$set[field + '.0.' + task] = 100
db
.collection("myCollection")
.updateOne({username:username}, updateObj);
Might work
For example, if I have an object like:
{"angeredoutsidecontrol":"1","difficultiespileup":"2"}
And then later in a for loop I can access the key of angeredoutsidecontrol , how can I get the value returned as 0, which would represent which place in the object this key is?
There is no guaranteed order for keys of an object.
Definition of object from an old - but still effective in this case - documentation:
4.3.3 Object
An object is a member of the type Object. It is an unordered
collection of properties each of which contains a primitive value,
object, or function. A function stored in a property of an object is
called a method.
If order really matters to you, use array instead. For example:
[{ "angeredoutsidecontrol": "1" }
{ "difficultiespileup": "2" }];
The order of JSON objects is not maintained, so you can't do this.
[Is the order of elements in a JSON list maintained?
var myMoods = ["angeredoutsidecontrol","difficultiespileup"];
and
myMoods.indexOf( 'angeredoutsidecontrol' )
gives you position in your list
Just started to learn react.js and javascript. I'm going through all the documentation on facebook's github, but got stuck with this.
In the handleCelsiusChange method of Calculator class in Lifting state up chapter there is this line:
this.setState({scale: 'c', value});
So scale will get the value 'c'. Okay. But what is this value being simply there? Shouldn't it be a key-value pair?
I've checked the explanation of setState():
The first argument can be an object (containing zero or more keys to
update) or a function (of state and props) that returns an object
containing keys to update.
But it says nothing relevant about this usage.
Thanks! :)
That's actually a feature of ES6. If the key matches an existing variable name you can use this shorthand syntax. So instead of writing value: value you can simply write value as key and variable name are the same.
Example with ES6
function getCar(make, model, value) {
return {
// with property value shorthand
// syntax, you can omit the property
// value if key matches variable
// name
make,
model,
value
};
}
The equivalent of the above in ES3/ES5
function getCar(make, model, value) {
return {
make: make,
model: model,
value: value
};
}
Example taken from http://www.benmvp.com/learning-es6-enhanced-object-literals/
That is a special shorthand notation from ES6, it means value: value, look here https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand for more details
I am receiving a JSON object from a http call and I am trying to extract values from it.
JSON object contains:
data:{"userid":"007", "role":"spy"}
I use the following code to assign role property to another variable followed by some console log checks:
currentUserRole = data.role;
console.log("type of data: "+typeof(data));
console.log("data: "+JSON.stringify(data));
console.log("user role: "+currentUserRole);
The logs produce:
type of data: object
data: [{"userid":"007", "role":"spy"}]
user role: undefined
Also I tried another method of assignment:
currentUserRole = data['role'];
But currentUserRole remains undefined. How can I set a property of a JSON object to a variable?
According to the second line of your log (the call to JSON.stringify()), your data is actually an array of objects:
[{"userid":"007", "role":"spy"}]
If it was an object as you are expecting, it would look like this:
{"userid":"007", "role":"spy"}
(the difference is subtle, but notice the missing square brackets)
Try this:
currentUserRole = data[0].role;
Obviously in production-ready code, you probably need to do some extra sanity checking to ensure that data is in fact an array containing at least one element.
It is a list. Try data[0].role
I've seen code that goes along the line of
Object( existingObject ).myMethod();
Is this different than calling existingObject.myMethod() directly? More generally, what does Object(x) do?
The Object constructor creates an object wrapper for the given value.
If the value is null or undefined, it will create and return an empty
object, otherwise, it will return an object of a type that corresponds
to the given value. If the value is an object already, it will return
the value.
In your case, since the value is an object already, it will just return the value existingObject. So, no, it is not really different from calling existingObject.myMethod directly.
Documentation