Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash .get replace empty value

so i am using lodash .get to copy some array from my database to create a excel documents by using this

object[key.key] = _.get(item, key.key, '-');

where key is set of array and key.key is set of array column name or field name. it works fine replacing undefined value from database to - but there is also some fields that just have an empty value and i want to catch those fields and also changing it into -

how to do that?

like image 677
PamanBeruang Avatar asked Mar 09 '18 14:03

PamanBeruang


People also ask

How do you remove undefined and null values from an object using Lodash?

To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNull or non-strict equality.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

Is null or undefined Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.

How do I check if an object is empty in Lodash?

The Lodash _. isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length.


1 Answers

If there won't be any other "falsy" values the shortest way would be:

obj[key.key] = item[key.key] || '-';

// or with lodash
obj[key.key] = _.get(item, key.key, '-') || '-';

This will replace every "falsy" value with a single dash.

If this isn't possible:

const value = item[key.key];
obj[key.key] = (typeof value === 'undefined' || value === '') ? '-' : value;

// or with lodash
const value = _.get(item, key.key, '-');
obj[key.key] = value === '' ? '-' : value;
like image 82
Andreas Avatar answered Oct 07 '22 00:10

Andreas