How to check req.body empty or not in node ,express? - javascript

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.

Related

Deleting an object from array of objects based on values of entire object

I have array of objects containing ids that look like this:
selectedParameters = [
{
operationID: "5f1def6a3f15e2fde38d8b13",
operatorID: "5f241ea9a28f1a5700bfb82a"
},
{
operationID: "5f1def6a3f15e2fde38d8b13",
operatorID: "5f241ea9a28f1a5700bfb829"
},
{
operationID: "5f1def6a3f15e2fde38d8b13",
operatorID: "5f241ea9a28f1a5700bfb828"
},
{
operationID: "5f1def7c3f15e2fde38d8b14",
operatorID: "5f241ea9a28f1a5700bfb82a"
},
{
operationID: "5f1def7c3f15e2fde38d8b14",
operatorID: "5f241ea9a28f1a5700bfb829"
},
]
I have a method which takes in an object having exact properties like above and then I want to check both operationID and operatorID of incoming object and delete that object from above array on exact match. I have a method that attempted to do that as shown below:
const deleteSelectedParameter = (removedParamObj) => {
selectedParameters.filter(
(selectedParam) =>
(selectedParam.operationID !==
removedParamObj.operationID) &&
(selectedParam.operatorID !== removedParamObj.operatorID)
)
};
However, I upon deleting it deletes multiple objects even though only one matches.
There is some error in the binary logic. You can try the following code:
const deleteSelectedParameter = (removedParamObj) => {
return selectedParameters.filter(
(selectedParam) =>
!((selectedParam.operationID === removedParamObj.operationID) && (selectedParam.operatorID === removedParamObj.operatorID))
)
};
This is a basic binary logic error.
What you want for filter()'s callback is this:
return false if opID equals and operID equals.
Which is return == !(opIDEq && operIDEq) == opIDNeq || operIDNeq.
What you did was return == operIDNeq && operIDNeq.
So basically, change your && to ||.

Converting Async Response to Standard Javascript Object

Imagine your React app gets a response like this:
email_address
first_name
last_name
What's a best practice way to convert these fields to something more common in Javascript:
emailAddress
firstName
lastName
Also keeping mind that there could be nested structures.
I've typically done this immediately when the response is received.
My colleagues seem to think it's fine to keep the snake_case syntax persist through the app.
There may be some edge cases that fail, I could not find anything on github that would do the trick but if you have any errors then please let me know.
It is assuming you only pass object literals to it, maybe you can write some tests and tell me if anything fails:
const snakeToCamel = snakeCased => {
// Use a regular expression to find the underscores + the next letter
return snakeCased.replace(/(_\w)/g, function(match) {
// Convert to upper case and ignore the first char (=the underscore)
return match.toUpperCase().substr(1);
});
};
const toCamel = object => {
if (Array.isArray(object)) {
return object.map(toCamel);
}
if (typeof object === 'object' && object !== null) {
return Object.entries(object).reduce(
(result, [key, value]) => {
result[snakeToCamel(key)] = toCamel(value);
return result;
},
{}
);
}
return object;
};
console.log(
toCamel({
arra_of_things: [
{ thing_one: null },
{ two: { sub_item: 22 } },
],
sub_one: {
sub_two: {
sub_three: {
sub_four: {
sub_four_value: 22,
},
},
},
},
})
);

How the java script complex object and complex array iterate?

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}

Null checking object not working

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'});
}

JavaScript - Performing a recursive search, value not being retained

I am trying to perform a search on an array of vehicles to see if any match the "Make" of "BMW".
Problem: While matches are found and result is given the value true, that value is lost as the function continues the loop. I thought I would be able to break out of the function, anytime a true value is found. The break is not working.
If I cannot break out of the function and must continue looping thru the remainder of that parent node's properties, how can I retain the true value, as once true is found, I am basically done with this node (vehicle).
Thanks
Here is a truncated look at my node tree:
[
{
"title": "2008 BMW 650",
"price": "30,995.00",
"type": "Coupes",
"details" : [{.....}],
"features" : [
{ ..... },
{ "name": "Make", "value": "BMW" },
{ ..... }
]
},
{ ..... }
]
let isPresent = recursiveFilterSearch(node, "Make", "BMW")
function recursiveFilterSearch(node, filterObj, filterValue) {
let result;
for (var key in node) {
// if the any node name & value matches, return true (on this vehicle)
if (node.name !== undefined) {
if (node.name === filterObj && node.value === filterValue) {
result = true;
break; // <-- not doing what I thought it would do
}
}
// if this node property is an array recursively loop thru the array's properties
if (result !== true && Object.prototype.hasOwnProperty.call(node, key)) {
var isArray = Object.prototype.toString.call(node[key]) === '[object Array]';
if (isArray) {
var childrenNode = node[key];
childrenNode.map(function (childNode) {
recursiveFilterSearch(childNode, filterObj, filterValue);
});
}
}
}
return result;
}
Struggled hard on this one, no help from those far smarter than I.
I hope this helps others.
I purposely did not do a search by features (as plalx above suggested), because I want to re-use this code on products that may not have a feature section. One can use this for any product, ie. from cars to shoes to TVs. The property names do not matter.
Make note I purposely lower-cased the respective variables, just to play it safe, as well as using indexOf on the value as my client has such values as "Automatic" & "6-speed Automatic", so index will pick up both when a search is done on "automatic".
collection-filter.js (javascript file)
function recursiveFilterSearch(node, filterObj, filterValue) {
let result = false;
for (const prop in node) {
if (node !== undefined) {
if (node.value !== undefined) {
node.name = (node.name).toLowerCase();
node.value = (node.value).toLowerCase();
if (node.name === filterObj && (node.value).indexOf(filterValue) > -1) {
result = true;
}
}
if (typeof(node[prop]) === 'object') {
recursiveFilterSearch(node[prop], filterObj, filterValue);
}
if (result) {
break;
}
}
}
return result;
}
module.exports = {
filterCollection(coll2Filter, filterName, filterValue) {
const results = [];
coll2Filter.map((node) => {
const isMatch = (recursiveFilterSearch(node, filterName.toLowerCase(), filterValue.toLowerCase()));
if (isMatch) {
results.push(node);
}
});
return results;
}
};
}
Inventory.js: (React.js file using alt flux)
import CollectionFilter from '../../components/forms/helpers/collection-filter.js';
render() {
if (!this.props.items) return <div>Loading ...</div>;
const products = this.props.items;
const result = CollectionFilter.filterCollection(products, 'Trans', 'Automatic');
return (
<div>{ result }</div>
)
.....
You do not assign the return value of your recursive call:
if (result !== true && Object.prototype.hasOwnProperty.call(node, key)) {
var isArray = Object.prototype.toString.call(node[key]) === '[object Array]';
if (isArray) {
var childrenNode = node[key];
childrenNode.map(function (childNode) {
// assign recursive result
result = recursiveFilterSearch(childNode, filterObj, filterValue);
});
}
}
As a side note:
Such a generic search functionality will work but if you are developing new functionality and you have full control over the json structure keep things like 'searchability' in mind.
Were the structure like:
{
features: {
make: "Opel",
ft2: ""
}
}
You could loop all object and search like:
if (car.features.make == "Opel") {
// found in one liner
}

Categories

Resources