Checking if an object exists via .length - javascript

JSFiddle: https://jsfiddle.net/pd08dgxu/1/
I need to check whether a JavaScript object is empty or not. Suppose, in this fiddle, Obj1 is not empty (it contains the fields below) but Obj2 is {}.
In both cases, when I check obj1.length or obj2.length, I get Undefined (see alert). Shouldn't we check for existence by using the .length operator on all variables, whether strings or complex objects?
function getObject() {
return { 'color' : 'red',
'title' : 'my title'
};
}
var myObj1 = getObject();
var myObj2 = {}; //empty object
alert('myObj1 Length = ' + myObj1.length + ' myObj2 Length = ' + myObj2.length);

You cannot check the object's existance using obj.length.
You have to count the number of keys.
Try Object.keys(Obj).length
function getObject() {
return { 'color' : 'red',
'title' : 'my title'
};
}
var myObj1 = getObject();
var myObj2 = {}; //empty object
console.log('myObj1 Length = ' + Object.keys(myObj1).length + ' myObj2 Length = ' + Object.keys(myObj2).length);

The length property only works like that on Arrays.
To get the number of properties on any object, you can use the Object.keys method, which returns an array of all the property-names on an object. Like this: Object.keys(Obj).length.

isEnum
Here is my conventional JavaScript singleton which is a part of all my util. libs.
function isEnum(x){for(var i in x)return!0;return!1};
And it's faster than Object.keys in any aspect. Will work correctly in case you've accidentally dropped an Array in its argument instead of an Object.
It's use is exactly what you need it for to check if the object is empty or enumerable before deciding to iterate it or not.

Related

Create JSON object accoring to request.body

Using NodeJs + Express to create a REST API. Everything works well, but I can't understand how to iterate through the request.body and check its fields for undefined and empty values and assign new object only with valid data.
request.body looks like:
{
key: 'value',
otherKey: 'otherValue',
oneMoreKey: '',
oneMoreKey2: undefined,
oneMoreKey3: null
}
At that end my object shoud look like:
let contactData = Object.assign({},{
'key': 'value',
'otherKey': 'otherValue'
})
Looking for your advices and help
JavaScript
function getCleanObject(oldObject) {
var newObject = {};
for (var property in oldObject) {
var value = oldObject[property];
if (value) newObject[property] = value;
}
}
Explanation
You can start off by creating a new clean Object
var newObject = {}; // same as new Object();
Then iterate through all of the object's properties using a for loop.
for (var property in oldObject)
Then get the value of that property
var value = oldObject[property];
If the value is Troothy add the property to the new Object
if (value) newObject[property] = value;
Note that this way the false value will be rejected. To allow it to be copied to the new Object you should replace the if statement with
if(value || value === false)
Moreover, if the Object you are copying also inherits from some other Object it is possible that it will have extra properties as well and if you do not want them to be included you should change the if statement to
if(value && oldObject.hasOwnProperty(value))
And Remember for(var item in object) != for(var item of list)
in is used to iterate through an object's properties whereas of is used to iterate through an iteratable (i.e. list). Also in is supported in all browsers whereas of is not supported by internet explorer.
your_object = {
key: request.body[key] || 'default',
otherKey: request.body[otherKey] || 'default',
oneMoreKey: request.body[oneMoreKey] || 'default'
...
}
explanation on how or (||) works JavaScript OR (||) variable assignment explanation

javascript: I need to get an object key from the function argument

vm.contributorAmountPerYear[index-1] gets me an object, and I want its key to be the year argument of the function.
function getAgriAmount(year,amount,index) {
if (typeof amount !== "number" ) {
amount = parseInt(amount ||0);
};
var argiYearlyLocalCost = vm.argiterraYearlyLocalCost;
console.log(vm.contributorAmountPerYear[index-1].year);
}
vm.contributorAmountPerYear[index-1][year]
For any javascript object, you should keep in mind that if you use . dot notation, you cannot access the properties for keys that come from a variable and are determined at runtime. Use square bracket notation [] for such a case. This should work:
vm.contributorAmountPerYear[index-1][year];
Dot notation should be used when you already know the key:
var cuteJavaScriptObject = {
animal : 'cat'
}
var myVar = 'animal';
console.log(cuteJavaScriptObject.animal); // OK
console.log(cuteJavaScriptObject.myVar); // Wrong !!
console.log(cuteJavaScriptObject[myVar]); // Now OK

returning the index name from JSON in JS

Imagine we have this JSON:
{ "A" : {"A1": "1" } }
How can I extract the actual index A1 ?
So that I can use it in JS like:
var index = "A1";
edit — in case you mean, "How can I extract the value at index A1", then you'd just use the dot or bracket operators:
var value = object.A.A1;
or
var index = "A1";
var value = object.A[index];
Else see below.
You can iterate through the property names of an object with the for ... in loop:
for (var propertyName in object) {
// ...
}
The loop will also include properties from the prototype chain, so you can avoid that (if you want) with a function called hasOwnProperty:
for (var name in object) {
if (object.hasOwnProperty(name)) {
// really is a local property
}
}
Newer browsers support a way to get the property names as an array:
var names = Object.keys( yourObject );
That list will only include "own" properties; that is, those for which hasOwnProperty() would return true.
Finally, there are ways that properties can be defined such that they're not "enumerable". Usually when that's done, you would generally not want to see them in for ... in anyway.

object Key in javascript class/dictionary?

I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

Categories