Check if object inside an object is empty with javascript [duplicate] - javascript

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 8 years ago.
Hello I have an object:
var equippedItems = {
weapon: {},
armor: {},
accessory: {}
};
I need a way to check if equippedItems.weapon equals to '' at some point I am doing something like equippedItems.weapon = ''; I dont know if it's exactly the same as above object. I already tried using object.hasOwnProperty but it seems I cannot use equippedItems.weapon in this case, maybe I am doing something wrong? Also note I did read how to check if object is empty already, but it didn't work for my object inside an object.
#Edit:
Like I said, I already read those and they did not give me a straight answer for my question, they did answer how to check if object is empty, but the object was like object = {}; while mine is like
object = {
object:{},
object2:{},
object3:{}};
Thats why it confuses me.

Just make use of Object.keys
function isEmpty(obj, propName){
return Object.keys(obj[propName]).length == 0;
}
Another way is to make use of JSON.stringify method which will return {} if empty
function isEmpty(obj, propName){
return JSON.stringify(obj[propName]) == "{}";
}
In both the cases, you would call the function like
if(isEmpty(equipmentItems.weapons)){
equipmentItems.weapons = "";
}

To check that an object has a property you can use:
"weapon" in equippedItems
or
equippedItems.hasOwnProperty("weapon")

Related

Best approach for determining if an object in reference is null [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
JavaScript, elegant way to check nested object properties for null/undefined [duplicate]
(4 answers)
Closed 5 years ago.
In JavaScript (or TypeScript), if I'm going to reference something like:
return myObj1.myObj2.myObj3.myProperty;
to be safe, I guard it with something like:
if (myObj1 && myObj2 && myObj3)
return myObj1.myObj2.myObj3.myProperty;
else
return null;
Is there a more concise way of just getting null from the above reference without surrounding it by an if?
Please note, since I'll be using this in a TypeScript app, some solutions may not work with dynamic object definition.
Thanks.
I'd use a library like lodash for this:
//gets undefined if any part of the path doesn't resolve.
const answer = _.get(myObj1, "myObj2.myObj3.myProperty");
//gets null if any part of the path doesn't resolve.
const answer2 = _.get(myObj1, "myObj2.myObj3.myProperty", null);
See https://lodash.com/docs/4.17.4#get for details.
You can define some temporary objects to substitute when a lookup fails.
return (((myObj1||{}).myObj2||{}).myObj3||{}).myProperty || null;
You can make a reusable object if desired.
const o = Object.create(null);
Then use it as needed.
return (((myObj1||o).myObj2||o).myObj3||o).myProperty || null;

Call sub function in object with variable brackets [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
var myObject = {
sub: {
myFunction: function() {
console.log('check');
}
}
}
var callFn = 'sub.myFunction'; // I want it to solve it here, whats going wrong?
myObject[callFn](); // Works, but not with 'sub.myFunction'
myObject.sub.myFunction(); // This works ofc.
I need a generic solution. Can someone explain why the sub.myFunction does not work? Does anyone have a workaround to solve this?
The . character is a valid part of a property name in javascript as long as you enclose it in quotes.
What that means to you:
myObject["sub.myFunction"] - looks for a property named sub.myFunction on myObject. It does not look for a property named myFunction on the sub property of myObject.
myObject.sub.myFunction - does not have the . in quotes so it's treated as a property accessor. That means we look for a myFunction property on the sub property of myObject.

JavaScript: store function method to variable [duplicate]

This question already has answers here:
JavaScript Function Context Incorrect
(3 answers)
Closed 7 years ago.
I have a variable a that can be either an object or an array of objects. I have an array array.
I want to append a to array, so I thought of using either Array.prototype.push.call or Array.prototype.push.apply with a ternary operator as follows:
var a = "hello"; // or var a = ["hello", "world"];
var array = [];
var append = ($.isArray(a)) ? Array.prototype.push.apply : Array.prototype.push.call;
append(array, a); // Uncaught TypeError: undefined is not a function
($ being jQuery)
I'm new to JavaScript and I guess there is a good reason why this doesn't work but I couldn't find it. Can't apply or call be assigned to a variable? (They are not real functions?) Or is something missing on the call to append()?
Note: I know I could do this with if/else but I'd rather like to understand why I can't assign these methods to a variable and call it.
Minor additional question: I want to do this because I get a from a JSON API and if I understand correctly, JSON can't contain arrays of one single object. Although I feel that what I'm trying to do must be very common, I also couldn't find how other developers deal with this. Is there a better way than testing whether a is an array or not and use apply() or not accordingly?
This happens because call and apply are instance methods. They are critical to the context object this.
Eventually you should execute append.call(Array.prototype.push, array, a) because call or apply need function push to be passed as this
You don't need any if, just use concat
var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);

Can anyone tell me what this javascript might be doing [duplicate]

This question already has answers here:
What does "options = options || {}" mean in Javascript? [duplicate]
(5 answers)
Closed 9 years ago.
So I am looking over a project which includes the following line of javascript:
window.negotiationApp = window.negotiationApp || {};
Can anyone explain might be going on with this line of code?
Update
So now that I understand what this line of code is doing, my question maybe unique in asking the following:
There is no negotiationApp object in the javascript code. window.negotiationApp will always be set to an empty object, it seems the developer is really just using this as a namespace or container for other objects. Is this a common javascript practice?
it makes sure that window.negotiationApp is set. If window does not have this property then it initializes it to be {} (an empty object), otherwise, it does nothing.
It's an idiom that basically means, if window.negotiationApp doesn't exist, set it to {}. You might do that so future info doesn't return undefined or something.
Ensures window.negotiationApp object is not undefined.
window.negotiationApp = window.negotiationApp || {};
Means if window.negotiationApp is defined then use it or assign window.negotiationApp an empty object.
if(window.negotiationApp) {
window.negotiationApp = window.negotiationApp;
}
else {
window.negotiationApp = {};
}
since this variable is set on the global scope, it makes sure not to override an existing one if there is any.
so it basically says, if there is already a negotiationApp variable defined - use it, if not create a new one.

How to check whether a Javascript object has a value for a given key? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I check to see if an object has an attribute in Javascript?
I have a Javascript object defined as following:
var mmap = new Object();
mmap['Q'] = 1;
mmap['Z'] = 0;
mmap['L'] = 7;
...
How to check whether this map has a value for a given key (for example 'X')? Does .hasOwnProperty() get into play?
if ('X' in mmap)
{
// ...
}
Here is an example on JSFiddle.
hasOwnProperty is also valid, but using in is much more painless. The only difference is that in returns prototype properties, whereas hasOwnProperty does not.
You can use:
(mmap['X'] === undefined)
Fiddle: http://jsfiddle.net/eDTrY/

Categories

Resources