i'm trying to check for null value , even when i know the values are null the loop still doesn't break. Cheers for any help
constructor(){
super();
this.state = {
warningMsg: 'No Warnings'
}
this.detail = {
name: null,
phone: null,
email: null,
location: null,
extraDetail: 'Default'
}
}
handleSubmit(){
const {DetailStore} = this.props;
for (let value in this.detail) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({warningMsg:'Check Input'});
break;
}
}
DetailStore.entDetail(this.detail);
console.log(DetailStore.getDetail,'Submitted');
}
The 'value' in your for loop is actually the property name. You need to check:
if (this.detail[value] === null)
What you actually want is:
const detailValues = Object.values(this.detail);
for (const value of detailValues) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({
warningMsg: 'Check Input'
});
break;
}
}
for..in loops iterate over the property names of the object, not the value of the property. If you want to iterate over object values, better to use Object.values instead:
if (Object.values(this.detail).some(value => value === null)) {
console.log('null found');
this.setState({warningMsg:'Check Input'});
}
Related
I have an object like this:
let obj = {'machine1':{'err':'404', switch:false},
'gadget1':{'err':'404', switch:true}}
Would not pass validation. => return false
let obj2 = {'machine2':{'err':'404', switch:false},
'gadget2':{'err':null, switch:true}}
Would pass validation. => return true
I want to return true when every key in the object in which the switch is set to true does not have any errors (see obj2). (For machine2 the '404' error does not matter, because the switch is set to false.)
I tried something like that, but didn't get far.
function try() {
for (x in obj) {
obj[x].filter(x=>y.switch === true)
}
}
Thanks for reading!
you could do something like the follow:
const test = obj => Object.keys(obj).every(k => !obj[k].switch || obj[k].err === null)
So you check if every key in the object has switch set to false or the err equal to null.
You can do it by usign entries and every helpers of Array, like this:
let obj = {
'machine1': {
'err': '404',
switch: false
},
'gadget1': {
'err': '404',
switch: true
}
}
let obj2 = {
'machine2': {
'err': '404',
switch: false
},
'gadget2': {
'err': null,
switch: true
}
};
const validate = (data) => {
return Object.entries(data).every(([key, value]) => !value.switch || value.err === null)
}
console.log(validate(obj));
console.log(validate(obj2));
Did you mean something like that?
let obj={
1:{
'machine':{'err':'404', switch:false},
'gadget':{'err':'404', switch:true}
},
2:{
'machine':{'err':'404', switch:false},
'gadget':{'err':null, switch:true}
}
}
I changed the facility a bit to make it easier.
var n=1;
while (n<=2) {
if(obj[n].machine.switch==true){
if(obj[n].machine.err!='404')
console.log('SUKCES')
else console.log('ERROR 1')
}
else console.log('ERROR 0')
if(obj[n].gadget.switch==true){
if(obj[n].gadget.err!='404')
console.log('SUKCES')
else console.log('ERROR 1')
}
else console.log('ERROR 0')
n++;
}
Results:
ERROR 0
ERROR 1
ERROR 0
SUKCES
let notStudent, name, isRegistered
if (studentDetail && studentDetail.fields) {
({ notStudent, name, isRegistered } = studentDetail.fields)
}
Is there a way to write this logic without an if statement or in a succinct way?
You can destructure in this way. The tricky thing is when there is no fields property on studentDetail then javascript can throw an error, to tackle that case, you can set default empty object using || operator.
let studentDetail = {
fields: {
notStudent: '1',
name: '2',
isRegistered: true
}
}
let {
notStudent,
name,
isRegistered
} = (studentDetail && studentDetail.fields) || {};
console.log(notStudent);
console.log(name);
console.log(isRegistered);
You can destructure an empty default object in case your studentDetail.fields doesn't exist:
const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};
Below is running code snippet for the javascript object and array.
I have one jsonObj and here the ResultElementLevel could be the array or
object.
According to I just put if else condition and compare if Array and 'object'.
My question is,How would it be possible without if else condition?
can we write one function which compare object and Array inside single if.
The jsonObj is populating dynamically.
Here it would be possible CHECK object is also come into the Array or Object.
var jsonObj = {
"Response": {
"Errors": {
"Check": {
"_attributes": {
"id": "51416",
"name": "lucyocftest090601"
},
"CheckLevel": {
},
"ResultElementLevel": {
"_text": "Line No (2) [Missing Reporting Category] "
}
}
},
"Success": {
}
}
}
iterateObjorArr(jsonObj);
function iterateObjorArr(jsonObj){
let checkArr = jsonObj.Response.Errors.Check;
let checkID = checkArr._attributes.id;
let checkName = checkArr._attributes.name;
let status = 'failed';
let resultElementLevel = checkArr.ResultElementLevel;
let errorUploadArr = [];
let errorUploadObj;
if (Array.isArray(resultElementLevel)) {
resultElementLevel.map(function (data, index) {
errorUploadObj = {
'id': checkID,
'checkName': checkName,
'status': status,
'errors/warnings': data._text
};
errorUploadArr.push(errorUploadObj);
});
} else {
if (typeof (resultElementLevel) === 'object') {
errorUploadObj = {
'id': checkID,
'checkName': checkName,
'status': status,
'errors/warnings': resultElementLevel._text
};
errorUploadArr.push(errorUploadObj);
}
}
console.log("errorUploadArr", errorUploadArr);
}
You can test to see if resultElementLevel has the length property or not using hasOwnProperty(). Arrays have a length while objects do not (generally):
if (resultElementLevel.hasOwnProperty('length')) {
// Handle it as an array
} else {
// Handle as an object
}
This will, however, only work if the object assigned to resultElementLevel is guaranteed to not have a length property.
My question is,How would it be possible without if else condition? can we write one function which compare object and Array inside single if.
I don't think you'd want to get rid of the condition, but being able to deal with the passed data the same way, wether it's an array, a single item, or null/undefined
You could normalize the data first
function toArray(value){
return value == null? []:
Array.isArray(value)? value:
//isArrayLike(value)? Array.from(value):
[value];
}
//Objects that look like Arrays
function isArrayLike(value){
return value !== null && typeof value === "object" && value.length === (value.length >>> 0);
}
so that from here on, you always deal with an Array:
let errorUploadArr = toArray(checkArr.ResultElementLevel)
.map(function(item){
return {
id: checkID,
checkName: checkName,
status: status,
"errors/warnings": item._text
};
});
var jsonObj = {
Response: {
Errors: {
Check: {
_attributes: {
id: "51416",
name: "lucyocftest090601"
},
CheckLevel: {},
ResultElementLevel: {
_text: "Line No (2) [Missing Reporting Category] "
}
}
},
Success: {}
}
};
iterateObjorArr(jsonObj);
function toArray(value) {
return value == null ? [] :
Array.isArray(value) ? value :
//isArrayLike(value)? Array.from(value):
[value];
}
//Objects that look like Arrays
function isArrayLike(value) {
return value !== null && typeof value === "object" && value.length === (value.length >>> 0);
}
function iterateObjorArr(jsonObj) {
let checkArr = jsonObj.Response.Errors.Check;
let checkID = checkArr._attributes.id;
let checkName = checkArr._attributes.name;
let status = "failed";
let errorUploadArr = toArray(checkArr.ResultElementLevel)
.map(function(data) {
return {
id: checkID,
checkName: checkName,
status: status,
"errors/warnings": data._text
}
});
console.log("errorUploadArr", errorUploadArr);
}
.as-console-wrapper{top:0;max-height:100%!important}
I have an object like this:
var user = {
id: 101,
email: 'jack#dev.com',
personalInfo: {
name: null,
address: {
line1: null,
line2: null,
city: null,
state: null
}
}
}
I would like to iterate the properties and check if its properties are null. If they are all null I want to set that property null. This means starting from address whose values are all null so set address = null, then name and address are both null so personalInfo should be set null etc...
So my Object ends ups like this:
var user = {
id: 101,
email: 'jack#dev.com',
personalInfo: null
}
You could iterate all key/value pairs and decrement a count for all null values for this level. If all values are null, return null, otherwise the changed object.
For checking the nested objects, take the value and the type and call the function again and assign the result to the key.
function setNull(object) {
var entries = Object.entries(object),
count = entries.length;
entries.forEach(([k, v]) => {
if (null === (v && typeof v === 'object' && (object[k] = setNull(v)))) {
count--;
}
});
return count
? object
: null;
}
var user = { id: 101, email: 'jack#dev.com', personalInfo: { name: null, address: { line1: null, line2: null, city: null, state: null } } };
console.log(setNull(user));
You could do this recursively like so:
function isAllNull(obj) { // this function checks if an object contain only null values, i.e. checks if it is a null object or not
for(var key in obj) {
if(obj[key] !== null) { // if there is at least one property that is not null
return false; // then the object doesn't qualify
}
}
return true; // otherwise if all properties are null
}
function nullify(obj) { // this function takes an object and replace all its null child objects with null
for(var key in obj) {
if(obj[key] && typeof obj[key] === "object") { // if the current value is an object
nullify(obj[key]); // nullfiy it first (turn its null children objects to null)
if(isAllNull(obj[key])) { // then check if it is a null object
obj[key] = null; // if so replace it with null
}
}
}
}
Example:
function isAllNull(obj) {
for(var key in obj) {
if(obj[key] !== null) {
return false;
}
}
return true;
}
function nullify(obj) {
for(var key in obj) {
if(obj[key] && typeof obj[key] === "object") {
nullify(obj[key]);
if(isAllNull(obj[key])) {
obj[key] = null;
}
}
}
}
var user = {
id: 101,
email: 'jack#dev.com',
personalInfo: {
name: null,
address: {
line1: null,
line2: null,
city: null,
state: null
}
}
};
nullify(user);
console.log(user);
Call this function by passing a object and it will return object as you need,
function setNulls(obj) {
var flag = false;
for (var key in obj) {
if (obj[key] != null && typeof obj[key] == "object") {
obj[key] = setNulls(obj[key]);
}
if (obj[key] != null) {
flag = true;
}
}
if (flag)
return obj;
else
return null;
}
Below is my request body and which is sending from client side
var credentials = {
"ConsumerData": {
"ConsumerStoreId": "a",
"ConsumerUserId": "a"
},
"CustomerData": {
"CustomerId": "2345678890"
},
"ErnD": {
"UID": "3",
"TxnDt": "1"
},
"PurD": [{
"ItemCode": "3456tghw3",
"ItemEANCode": "223222122"
},
{
"ItemCode": "8jghw3865",
"ItemEANCode": "3334443222"
}
]
}
for testing i am sending var credentials = {} empty credentials
In server side controller(node,express) i want to check req.body empty or not
if(!req.body)
{
console.log('Object missing');
}
if(!req.body.ConsumerData.ConsumerStoreId)
{
console.log('ConsumerStoreId missing');
}
if(!req.body.CustomerData.CustomerId)
{
console.log('CustomerId missing');
}
if(!req.body.ErnD.UID)
{
console.log('UID missing');
}
console.log('outside');
i am checking everything but alwasys its printing outside only
ES2015:
if(req.body.constructor === Object && Object.keys(req.body).length === 0) {
console.log('Object missing');
}
PRE ES2015:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return JSON.stringify(obj) === JSON.stringify({});
}
if(isEmpty(req.body)) {
console.log('Object missing');
}
For more ways in a pre es2015 style: https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty
if (Object.keys(req.body).length === 0) {
// Do something
}
When the req.body is empty, it returns an empty object, as such, making !req.body return false even when it's empty. Instead, you should test for !Object.keys(req.body).length. What it will do is take every key from the object and count, if no keys where found it would return 0. Then all we need to do is use the same method that we use on empty arrays, testing for !arr.length making it possible to receive a boolean stating it's fullness or the lack of it.
Then, we end up with the code:
router.post('/auth/signup', function(req, res) {
if(!Object.keys(req.body).length) {
// is empty
} else if(!req.body.param1 || !req.body.param2 || !req.body.param3) {
let params = [req.body.param1, req.body.param2, req.body.param3];
let lackingParam = params.findIndex(param => !param === true) > 0 ? params.findIndex(param => !param === true) > 1 ? "req.body.param3" : "req.body.param2" : "req.body.param1";
// lacking only lackingParam
} else {
// not empty
}
});
What about using lodash.isempty
const isEmpty = require('lodash.isempty');
if(isEmpty(req.body)) {
console.log('Empty Object');
}
Here are the docs https://lodash.com/docs/4.17.11#isEmpty
Checks if value is an empty object, collection, map, or set.
Objects are considered empty if they have no own enumerable string
keyed properties.
Array-like values such as arguments objects, arrays, buffers, strings,
or jQuery-like collections are considered empty if they have a length
of 0. Similarly, maps and sets are considered empty if they have a
size of 0.