I have an array of objects, say memberToChange.checkboxes: ICheckbox[] like this:
Now, I have a variable, say internalNumber: string which has the value "3419". I want to get the object from the array of objects where the internalNumber matches the label property. Ultimately, I want to set the value attribute of that object to true.
My code is:
let checkboxes = _.find(scope.selectedMembers, (member: IMember) => member.member.uuid === memberId).checkboxes; //gives me array of checkboxes.
let checkboxToChange = _.find(memberToChange.checkboxes, function(checkbox: ICheckbox){
return (checkbox.label === internalNumber);
}); //gives me null, moreover, even a console.log inside the second find doesn't print. I'm thinking the two consecutive _.find statements are messing something up, not sure what.
For reference, this is my ICheckbox interface:
export interface ICheckbox {
label: string;
sublabel?: string;
value: boolean;
numberUuid: string;
}
I would expect that for internalNumber 3419, it should return me the second object from the array. But it returns undefined. I'm not sure what's going on here.
If there is a better way to find and set the value to true in one go only, I'd be happy to know that as well.
Any help is appreciated. Thank you.
Update:
After someone suggested using filter method of javascript, I tried this: (my scope is assigned to this)
scope.selectedMembers.filter(function(member) {
if (member.member.uuid === memberId) {
scope.memberCheckboxes = [];
console.log('found member'); //prints
scope.memberCheckboxes = member.checkboxes;
console.log(scope.memberCheckboxes); // print correctly, with checkboxes of the member
scope.memberCheckboxes.filter(function(checkbox) {
console.log('inside checkbox function'); //control doesnt even come here
if (checkbox.label === intNum) {
console.log('found checkbox'); // control doesnt come here
}
});
}
});
Here, I don't understand why the first console.log inside scope.memberCheckboxes.filter doesn't print? Am I missing something obvious here?
By some reason your memberToChange.checkboxes (or member.checkboxes in your updated question) have no elements.
It is the only explanation why it does not work since your code is otherwise correct. The fact that console.log('inside checkbox function') does not print confirms that.
Related
although it is a very simple code, I would like to get a full understanding of what is happening in my condition:
let getFreqOn = function(string){
//set a variable for object
let object = {}
for (let key = 0; key < string.length; key++){
// if (object.hasOwnProperty(string[key])) {
// if (object[string[key]]) {
// if (object[string[key]] !== undefined) {
if (string[key] in object) {
object[string[key]]++
}
else{
object[string[key]] = 1
}
}
return object
}
My main concern would be the first condition, I understand what it is they do but I cant put in to plain English how it is working. For example if (string[key] in object) is basically telling my that if a specific property is in the empty object I defined, then I will set then it will be set as the property and incremented. But what I'm trying to wrap my head around is that the object is empty, so how can the property be in the object?
Hoping someone can enlighten me on the conditions that I commented out as well. Sorry for the noob question.
First, the in operator returns a boolean result. It checks whether the string on the left is present as a property name in the object on the right.
Thus
if (string[key] in object)
asks whether that single character of the string is in use as a property name in the object. As you observed, the very first time through the loop that cannot possibly be true, because the object starts off empty.
Thus the if test is false, so the else part runs. There, the code still refers to object[string[key]], but it's a simple assignment. An assignment to an object property works whether or not the property name is already there; when it isn't, a new object property is implicitly created.
The key difference is right there in the two different statements from the two parts of the if - else:
object[string[key]]++; // only works when property exists
object[string[key]] = 1; // works always
I'm having trouble figuring out how to customize console.log() so that it automatically prints out the label for each argument I pass into it. For example, I often do something like this, so that it's clear what each log is printing out:
console.log('firstName: ', firstName);
I would love to be able to simplify this to:
my.log(firstName);
Is there any way to pass the variable names of the caller args into console.log()? Or is there another way to do this? My wish is that I don't have to type out the variable name twice, just the once. And ideally print out multiple arguments each with its own label on its own line in the console. I'm aware that I can access the arguments list, but I don't know how to un-eval() each argument to get just its variable name, if that makes sense. I'm hoping it's something super-easy I missed.
Doing it the way you want is impossible (the log function doesn't know what name you called things.)
The way I work around this is to use the object shorthand {firstName}to create a temporary object.
You can then either use .log or .table to display it:
const firstName = 'bob';
console.log({firstName});
console.table({firstName});
// It also works for multiple variables:
const lastName = 'smith';
console.log({firstName, lastName});
You could use console.table() to print things in a more readable form:
(Look in the real console to see it.)
var obj = {
firstName: "name",
lastName: "smith"
};
function log(obj) {
console.table(obj);
}
log(obj);
Try this :
var my = {
log : function(name) {
console.log('firstName: ', name);
}
};
my.log("Rohit");
I have an object that I am passing to a function, that I am trying to figure out if the property exists or not, and when it doesn't, ignore it.
The problem is I keep getting false even when the property is there. For sake of example, I will use an object I posted on another question earlier today...
var myObj = {
something1_max: 50,
something1_enabled: false,
something1_locked: true,
something2_max: 100,
something2_enabled: false,
something2_locked: true,
something3_max: 10,
something3_enabled: true,
something3_locked: true
}
which gets passed to a function like: buildRetentionPolicyStr('something2', myObj);
So far I’ve got everything I need with this function working perfectly. Until I tried it on live data and realized on the occasion, properties I thought were static and there with defaults otherwise aren't always actually there. So I need to do something I assume with hasOwnProperty() somehow. So in my function I can set a default of my own where if the property exists, use it..
I.e.:
function buildRetentionPolicyStr(theScope, obj)
{
var myVar = 0;
if(obj.hasOwnProperty(theScope + '_enabled'))
{
myVar = obj[theScope + '_enabled'];
}
}
In my current test case, the object does in fact exist, so I know that to be true. However, when I do (right above the if statement):
console.log(obj.hasOwnProperty(theScope + '_enabled'));
// Or
console.log(obj.hasOwnProperty([theScope + '_enabled']));
I get this output respective to the order above:
false
// Or
["something2_enabled"]
What is, if there is one, the proper way to check to see if the property exists in this fashion?
A simple way to do that is to run typeof against your property:
obj = { xxx: false }
typeof obj.xxx // 'boolean'
typeof obj.yyy // 'undefined'
I ended up doing a review of my code to figure out overall that I had some mix matched cases. While I was in all doing what I should have, I overwrote one of my variables and caused the object I was looking for to essentially to end up going missing. So in fact false was correct.
So to verify the how or which was proper for me in my case.
obj.hasOwnProperty([theScope+'_enabled']);
was the proper way.
I am trying to run some JavaScript, but it is not working.
I have an object with two properties that are also objects.
var people = {
me: {
name: "Hello"
},
molly: {
name: "Molly"
}
};
And I am trying to make a function that uses a for/in statement and an if statement to list the properties of people.
var search = function (x) {
for (var a in people) {
if (people.a.name === x) {
return people.a;
}
}
};
So the function loops through the properties of people and assigns them to the variable a. Therefore people.a will be equal to a property of people. Then the function returns the property (people.a).
So if I type in me as parameter x, will the function should return the properties for the me object? I put this code in jsLint and jsHint and it passed, but I decided to remove the corrections because they were useless.
I then want to print the object properties in the browser:
var print = search("me");
document.getElementById("p").innerHTML(print);
I have this linked to an html document, with a tag id "p". I have tested javascript in the html document already, so I know that the javascript document is linked properly.
But the code will not work. Does anyone have any suggestions?
I have it working now thanks to the answers. But I thought that it would only print "Hello" to the screen, not { name: "Hello"}.
You need to use people[a], not people.a. The former looks for a property with the name of the value stored in a; the latter looks for a property literally named "a", which of course doesn't exist.
for (var a in people) {
if (people[a].name === x) {
return people[a];
}
}
Fiddle here.
Also, I think you meant search("Hello"), right? If not, then it would just be var search = function(x) { return people[x]; }.
people.a.name
you need to use the bracket operator if you want to access an item by name. Using people.a is literally searching for a member named 'a' instead of a member with the same name as the value of a.
Try:
people[a].name
instead.
4 errors in your code:
replace people.a with people[a]
replace innerHTML() with innerHTML
set HTML like this: document.getElementById("p").innerHTML = print.name;
As in a previous answer, search by name
Code: http://jsfiddle.net/nabil_kadimi/vVSPG/
I want to be able to call a function in JavaScript and return a primitive value, but also data. For instance, let's say I want to validate a password. Sometimes I want to know if it's valid or not (meets minimum requirements), and sometimes I want to know how strong it is, and other times I want to know how strong it is in words ("weak, strong,", etc.).
So basically I want this to be valid:
if (validate.checkPassword(password)) ...
but also this to work:
if (validate.checkPassword(password).strength === "strong")
if (validate.checkPassword(password).rating >= 6)
Since an object can both be a function have data, can a JSON return value both have a primitive type base value, and other data members?
No, things can not be multiple typed. However, you could add a boolean to that data structure
if (validate.isValidPassword(passWord).isValid)...
but you should strongly reconsider your nomenclature, as that is some confusing stuff up there.
Otherwise, null is falsey, so if you only use the latter statements inside a block where it is valid, then you should have no problem.
First off, JSON is just the notation of a JavaScript object not what the object itself is called. Within JavaScript (unserialized) it's just an object.
With that said, it seems like you want to return an object back from your validation method which would then expose the various information you're looking to return. e.g.
function isValidPassword(pw){
var result = {
strength: 'weak',
rating: 0,
valid: false
};
// test and change result.strength, result.rating and result.valid
// based on the input
return result;
}
This is an either/or scenario so you can't return "true/false" and get that extra meta information. Note that any object returned would result in a true result when tested, so given the above:
var validPassword = validate.isValidPassword(null);
// always true, we have an object
if (validPassword){
}
// instead, you'd now need to check:
if (validPassword.valid){
}
(I'll also disregard that a name like isValidPassword implies a true/false result and not an object result so if you're making a common library I'd encourage you to rename the function if you plan to change the result)
However, you can make multiple methods to break out the level of detail you're looking for, which makes a simple isValidPassword work as intended, but then add functionality like getPasswordStrength, getPasswordRating, etc.:
function isValidPassword(pw){
// return true/false;
}
function getPasswordStrength(pw){
// return "weak","strong",etc.
}
function getPasswordRating(pw){
// return 1,2,etc.
}
This also keeps the implied results a little more legible in terms of readability while still offering alternatives to getting the information you're looking for.
if (!validator.isValidPassword(pw)){
error = pw + ' is unacceptable (' + validator.getPasswordStrength(pw) + ')';
}
return { strength: 'abc', rating: -1 }
Truthyness in javascript will make the if statement work, then you can inspect the JSON for any values needed.
Consider:
function PasswordInfo(strength, rating)
{
this.strength = strength;
this.rating = rating;
}
function isValidPassword(password)
{
return new PasswordInfo('strong', 10);
}
function validate()
{
var info = isValidPassword('password');
if (info.strength === 'strong' && info.rating >== 6)
{
alert('good password);
}
else
{
alert('bad password);
}
}
The function PasswordInfo in this instance is actually a class/constructor.
As far as I know, you can only return one 'thing' from your function, but the function can contain other 'things'.
I think your best result would be to return an object along these lines:
{
valid:
strength:
rating:
}
Then you could do what you're wanting above, with the exception of the default type where you'd need to do:
if (validate.isValidPassword(password).valid)
EDIT: As a slight justification to returning an object each time. In my mind I had imagined you would always want to check the state of why a password was valid or not. Simply returning false would give you the y/n for whether it passed, but wouldn't give you the info you'd need to establish 'why' the password was not valid.
If you wanted to display some 'you must include uppercase, lowercase and ensure that the first letter was typed on a Monday' type message then it would seem sensible to return the password 'result' object in every situation. Just seems more flexible to me.