Remove just undefined (not null) [duplicate] - javascript

This question already has answers here:
How to remove undefined and null values from an object using lodash?
(27 answers)
Closed 5 years ago.
I am using library Lodash and I need from my javascript object remove just possible undefined properties, but I want keep null properties.
for example if I would have object like this:
var fooObject = {propA:undefined, propB:null, propC:'fooo'};
I expect output like this:
{propB:null, propC:'fooo'}
I tried this:
.pickBy(fooObject, _.identity);
but it remove also null values. Does Lodash contain some function for that? Thanks.

Try with:
_.pickBy(fooObject, v => v !== undefined)

Return anything that is NOT _.isUndefined :
_.pickBy({propA:undefined, propB:null, propC:'fooo'}, function(val){
return !_.isUndefined(val);
});
Or even more nicely :
_.omitBy({propA:undefined, propB:null, propC:'fooo'}, _.isUndefined);

Try using .omitBy method .
For undefined and null values.
_.isUndefined and _.isNull
var fooObject = {propA:undefined, propB:null, propC:'fooo'};
To remove undefined values from object
var newObj= _(fooObject).omitBy(_.isUndefined).value();
console.log(newObj);
Incase,If you want to remove both undefined and null
var result = _(fooObject).omitBy(_.isUndefined).omitBy(_.isNull).value();
console.log(result);
Hope this helps..!

//simple javascript
var fooObject = {propA:undefined, propB:null, propC:'fooo'};
for(var prop in fooObject)
{
if(fooObject[prop]===undefined)
delete fooObject[prop];
}
console.log(fooObject);

Related

How to access props inside a filter with an argument in React [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }

Can't use a string in an object path [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
I have this code :
success(JSON.parse(xhr.responseText).items[0].snippet.title);
The problem is I can access what I want with this but I'd like to be able to do this :
var path = 'items[0].snippet.title';
success(JSON.parse(xhr.responseText).path);
And it doesn't work :(
It's probably nothing but I can't figure out why.
Thanks!
For accessing object properties by string you need to use [ ] notation:
var foo = {bar : 2};
foo['bar']; // 2
But that won't work for nested properties, here is the approach I would follow using Array.reduce and ES6:
let path = 'items.snippet.title';
let response = JSON.parse(xhr.responseText);
let result = path.split('.').reduce((pre,cur) => {
return pre[cur];
}, response);
success(result);
In the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.
const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring.
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);

filtering on arrays in arrays, is there an elegant way of doing this? [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 5 years ago.
This one has always served me well...
var myProperty = "FOO"
var expenseSelect = expenseArray.filter(function(obj){
return obj.property == myProperty
});
But now I have a situation where the obj.property is an array of properties ["FOO", "BAR", "WEE"] inside the expenseArray.
Is there a smart way to do this? Or do I have to do the whole loop inside loop thing?
If you want to check if myProperty is in the array you can do it using
var myProperty = "FOO"
var expenseSelect = expenseArray.filter(function(obj){
return obj.property.includes(myProperty);
});
using the some() method tests whether at-least one element in the array passes the test implemented by the provided function, it can be a simple an option..
var myProperty = "FOO";
var expenseArray=[];
expenseArray[0]={ property: ["FOO", "BAR", "WEE"] };
expenseArray[1]={ property: ["NoFOO", "BAR", "WEE"]} ;
var expenseSelect = expenseArray.filter(function(obj){
return obj.property.some(function(element,index,array){
return element == myProperty;
});
});
console.log(expenseSelect);

Using an empty object as a parameter to a conditional if loop [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
This is similar to what I have been trying to do,
var obj = {};
if(obj){
//do something
}
What i want to do is that the condition should fail when the object is empty.
I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.
You could use Object.keys and check the length of the array of the own keys.
function go(o) {
if (Object.keys(o).length) {
console.log(o.foo);
}
}
var obj = {};
go(obj);
obj.foo = 'bar';
go(obj);
You can check if the object is empty, i.e. it has no properties, using
Object.keys(obj).length === 0
Object.keys() returns all properties of the object in an array.
If the array is empty (.length === 0) it means the object is empty.
You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.
working example
var myObj = {};
if(Object.keys(myObj).length>0){
// will not be called
console.log("hello");
}
myObj.test = 'test';
if(Object.keys(myObj).length>0){
console.log("will be called");
}
See details of Object.keys

JS using a variable name as a key in an array [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }

Categories

Resources