I have two condition of my same JSON data:
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[
{
"letterNo":13,
"letterId":1,
"inout":"out",
"inoutNo":"12332466544",
"inoutDate":"2070-01-01",
"letterIssuedSubBy":null,
"letterFile":null,
"representativeName":null,
"representativeNameEng":null,
"selectionId":124,
"assessmentNo":null,
"entryBy":"user98",
"rStatus":"I",
"others":null,
"signatary":"qwerrt",
"letterBox":null,
"imageFile":null,
"imageTitle":null,
"reminderYesNo":"N"
}
]
}
Same JSON with letter array empty structure :
{
"selectionId":124,
"selectionDate":"2070-01-01",
"selectionAudit":null,
"letter":[]
}
All these values are stored in
var trDataSecondTable; . I tried to compare if the letter is empty or not by using if condition:
if(trDataSecondTable.letter != null) {
console.log("asasfasdfdsfdsfds");
$("#inoutDate").val(trDataSecondTable.letter[0].inoutDate);
$("#inoutNo").val(trDataSecondTable.letter[0].inoutNo);
$("#signatary").val(trDataSecondTable.letter[0].signatary);
}
else
{
console.log("entered in else part");
}
Though "letter":[] is empty it is not entering into else part. While comparing i also tried trDataSecondTable.letter.length != 0 but also it is not entering into else part.
Your condition should check for both null and the length:
if (trDataSecondTable.letter != null && trDataSecondTable.letter.length > 0)
Is is important to check for null before accessing the length property as it guarantees you won't try to access the length property on null, which would raise an exception. This is important since data is rarely reliable.
Because of the && operator, if the first check fails, the second check won't be evaluated.
Actually, an even safer way would be to check if the value is truthy, as this will work for null and undefined:
if (trDataSecondTable.letter && trDataSecondTable.letter.length > 0)
You could check the length of the array.
if (trDataSecondTable.letter.length) {
// letter has some elements
} else {
// no elements
}
I think this condition is enough
if(trDataSecondTable.letter.length)
Related
I'm a super green developer that started my first job last week. I got a comment from another developer to add a condition to check if array is undefined and to check if array is in fact an array.
Initially I used:
$: hasActiveCoupons = $cart.coupons && $cart.coupons.length > 0;
if (hasActiveCoupons && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}
But then she pointed out to me that $cart.coupons.length > 0 would return a falsey value. And corrected it by writing:
if ($cart.coupons?.length && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}
So I am wondering how this works? I tired reading a few other questions but I don't fully grasp this concept.
$cart.coupons.length > 0 will return a falsey value if coupons is empty, but there is no need to check length this way in this case. A smaller approach to this flow would be the following:
$cart.coupons?.find(({ id }) => id === couponCode);
If coupons is undefined, undefined is returned.
If no values satisfy the testing function inside find, undefined is returned.
Therefore, no need to test length separately.
I am sending array of objects to server and trying to validate it, but I fail it will not do anything, if array is empty or neither it is valid, it just does not work, and I want to know why?
Here is code I use:
const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
ingredient.trim().length == 0 || quantity.trim().length == 0
})
if(ingredientValidator){
return res.status(409).send({
message: 'fully point ingredients'
})
}
what is problem with this?
P.S example of array of objects:
[
{
ingredient:'foo',
quantity:'bar'
},
{
ingredient:'foo',
quantity:'bar'
},
{
ingredient:'foo',
quantity:'bar'
}
]
How do I solve the problem?
I think you just need to alter the return of ingredientValidator:
const ingredientValidator = ingredients.some(({ingredient, quantity})=>{
return ingredient.trim().length == 0 || quantity.trim().length == 0
});
// or
const ingredientValidator = ingredients.some(({ingredient, quantity})=>
ingredient.trim().length == 0 || quantity.trim().length == 0
);
When you have curly brackets after the arrow, it's essentially a normal function block that needs a return in order to pass anything out. You can also just remove the curly blocks and it should act as expected to get the implicit return.
I am looking to optimize the below piece of code using Lodash. I have looked for solutions online, but could not find anything relevant. Can someone please help?
if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
if (form && form.application && typeof form.application.disclosureAccepted !== 'undefined' && form.application.disclosureAccepted !== null && !form.application.disclosureAccepted) {
return $q.when(response.data.content);
}
}
if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
const discAcc = _.get(form, ['application', 'disclosureAccepted'], true);
if (!_.isNil(discAcc) && !disAcc) {
return $q.when(response.data.content);
}
}
Basically, with _.get, you don't have to worry about checking a property of undefined, since it will just return undefined in that scenario rather than throw an error. _.isNil check is the value is both null or undefined, and then you want to make sure the value is still falsey.
I mean, I'm not sure if lodash "optimizes" in this case, since these function calls will actually slow it down, but it is slightly more readable. Like the comments, I'm not sure exactly why you need to be so specific; you could just use _.get(form, ['application', 'disclosureAccepted']) == false, thought I sway against using unstrict equivalence.
Seem to be having a little trouble getting some validation to work.
Currently trying to implement a system that will redirect a user if a variable is false, AND a form contains 0000 or 1111.
Example:
if xml_response == "false" && form == ("0000" || "1111") {
window.location.replace("");
} else {
submit.form
}
I've been able to get it working for 0000. If XML generates false, and form contains 0000, successful redirection.
If XML generates false and form contains 1111, no dice. I'm thinking it has to do with how I'm formatting my operators. Any ideas?
Here's my statement:
if (response == "false" && document.forms['Form'].id.value==("0000" || "1111") ) {
window.location.replace("http://url/");
} else {
document.getElementById("submit_form").submit();
}
That's invalid, you have to check for each value individually
if ((xml_response == "false") && (form == "0000" || form == "1111")) {
window.location.replace("");
} else {
submit.form
}
Note that you're checking for the string false and strings that look like numbers.
There's also the option to check an array for multiple values
if (
( response == "false" ) &&
( ['0000','1111'].indexOf(document.forms['Form'].id.value) != -1 )
)
{
window.location.replace("http://url/");
} else {
document.getElementById("submit_form").submit();
}
or even
/(0000|1111)/.exec(document.forms['Form'].id.value)
Note that:
document.forms['Form'].id.value
will attempt to find a form in the document with a name or ID of "Form". If it finds one, it will access it's ID property, which is a string, and attempt to read it's value property. Strings don't have a "value" property, so the result will be the value undefined.
I have an array of objects that presents as follows:
0: Object
ConsolidatedItem_catalogId: "080808"
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "Test Catalog Item"
ConsolidatedItem_imageFile: "27617647008728.jpg"
ConsolidatedItem_itemNumber: "1234"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "CAT"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
1: Object
ConsolidatedItem_catalogId: ""
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "ALARM,SHUTDOWN SYSTEM,AXIOM,XP3, 0-1500 PSIG, HIGH AND LOW PRES Testing"
ConsolidatedItem_imageFile: ""
ConsolidatedItem_itemNumber: "10008"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "INV"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
I'm trying to update and remove an object if it's added again, or update the object. Preferably update the object with the new value. My code is as follows:
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
console.log(result);
if (result.length == 0) {
finalObject.push(o);
shoppingCounter = finalObject.length;
$('#numberShoppedItems').text(shoppingCounter);
console.log(finalObject);
} else if (result.length == 1) {
finalObject.filter(function(x){
result = x;
console.log(result);
return x == result.ConsolidatedItem_itemNumber;
});
} else {
alert('Multiples Found');
}
}
I've tried multiple ways of getting the exact object and manipulating the data, however they've all failed. I would prefer to update the object, say if CatalogItem_itemNumber held the same value, if the CatalogItem_quantity was different - add the CatalogItem_quantity values together and update the array of objects.
I don't need an exact answer, a nudge in the right direction would do wonders though. I've looked at several of the related questions over the past couple of hours but none of them seem to address the issue. If you know of a question that has an answer, feel free to just link that as well. I may have missed it.
No Underscore.js please
When you find the matching record, you may update it by using $.extend
$.extend(result[0], o)
This will update the object in finalObject array in-place.
Alternatively, if you want to use the filter, you will need to insert the new object in the array.
finalObject = finalObject.filter(function(x) {
return x !== result[0];
});
finalObject.push(o)
Here we are allowing all the records that are not not equal to result to be returned in the resultant array that is received in finalObject. In next line, we are adding the new record.
Solved in the following manner:
1.) Verify object is not empty.
2.) Use .some() on object to iterate through it.
3.) Check if the finalObject, which is now e, has a match for the key in my temporary object I assemble, o.
4.) Update the values that need updating and return true;
Note: Originally I was going to remove the object by its index and replace it with a new object. This too can work by using .splice() and getting the index of the current object in that array you're in.
Here is the updating version:
if (o.ConsolidatedItem_quantity != '') {
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
if (result.length == 0) {...}
else {
finalObject.some(function (e) {
if(e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber){
var a;
a = +e.ConsolidatedItem_quantity + +o.ConsolidatedItem_quantity;
e.ConsolidatedItem_quantity = a.toString();
document.getElementById(o.ConsolidatedItem_itemNumber).value=a;
return true;
};
});
}
}