Check If an Object Exists

Check if object exists in JavaScript

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}

Test if an object exists JavaScript

If myObject[dynamicName] doesn't exist, you can't access its properties. Trying to access or assign a property of undefined causes an error.

You need to create the object, then you can create the property

if (myObject && myObject[dynamicName] && myObject[dynamicName].object !== undefined) {
alert("The object already exists");
} else {
myObject = myObject || {};
myObject[dynamicName] = myObject[dynamicName] || {};
myObject[dynamicName].object = something;
alert("The object didn't exist, so we populated it");
}

Check if object already exists in object

To get the property name of an object you can use Object.keys(). The first problem solved.

Now we need to iterate through the whole object including nested objects. This is the second problem.

And compare it to a query object. This is the third problem.

I assume that we have an object that only contains "simple" though nested objects with primitive values (I do not consider objects with functions or arrays)

// let's assume we have this object
const information = {
city: {
Streetname: 'streetname1'
},
house: {
color: "blue",
height: 100,
city: {
findMe: { Streetname: '' } // we want to get the path to this property 'findMe'
}
},
findMeToo: {
Streetname: '' // we also want to get the path to this proeprty 'findMeToo'
},
willNotFindMe: {
streetname: '' // case sensetive
}
}

// this is our object we want to use to find the property name with
const queryObject = {
Streetname : ''
}

If you use === to compare Objects you will always compare by reference. In our case, we are interested to compare the values. There is a rather extensive checking involved if you want to do it for more complex objects (read this SO comment for details), we will use a simplistic version:

// Note that this only evaluates to true if EVERYTHING is equal.
// This includes the order of the properties, since we are eventually comparing strings here.
JSON.stringify(obj1) === JSON.stringify(obj2)

Before we start to implement our property pathfinder I will introduce a simple function to check if a given value is an Object or a primitive value.

function isObject(obj) {
return obj === Object(obj); // if you pass a string it will create an object and compare it to a string and thus result to false
}

We use this function to know when to stop diving deeper since we reached a primitive value which does not contain any further objects. We loop through the whole object and dive deeper every time we find a nested object.

function findPropertyPath(obj, currentPropertyPath) {
const keys = isObject(obj) ? Object.keys(obj) : []; // if it is not an Object we want to assign an empty array or Object.keys() will implicitly cast a String to an array object
const previousPath = currentPropertyPath; // set to the parent node

keys.forEach(key => {
const currentObj = obj[key];
currentPropertyPath = `${previousPath}.${key}`;

if (JSON.stringify(currentObj) === JSON.stringify(queryObject)) console.log(currentPropertyPath); // this is what we are looking for
findPropertyPath(currentObj, currentPropertyPath); // since we are using recursion this is not suited for deeply nested objects
})
}

findPropertyPath(information, "information"); // call the function with the root key

This will find all "property paths" that contain an object that is equal to your query object (compared by value) using recursion.

information.house.city.findMe
information.findMeToo

How can I check if object exists in array of objects and update quantity?

You need to check all objects and exit the function if one item is found for incrementing the quantity.

If not found push the object.

var objArray = [{ name: "bike", color: "blue", qty: 2 }, { name: "boat", color: "pink", qty: 1 }],    carObj = { name: "car", color: "red", qty: 1 },    bikeObj = { name: "bike", color: "blue", qty: 1 };  function checkAndAdd (obj) {    for (var i = 0; i < objArray.length; i++) {        if (objArray[i].name === obj.name) {            objArray[i].qty++;            return;                             // exit loop and function        }    }    objArray.push(obj);}
checkAndAdd(carObj);console.log(objArray);
checkAndAdd(bikeObj);console.log(objArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Check if sub-object exists before using it

Since 2020:

The best way to solve this is using the Optional Chaining Operator

if(apple?.details) // Undefined if apple does not exist

Suggestion of lodash is no longer required when using runtime compatible with ES2020 i.e. Most browsers today & node>14.5

Check if object exists in another object tree in javascript

You cant simply compare objects using "in" operator. You can iterate the whole object and match values. Or simply match all values in objects.

**Sample **

let data = [
{
name: "Jade",
role: "admin",
pass: "0000",
},
{
name: "Jon",
role: "user",
pass: "0000",
},
{
name: "Adam",
role: "user",
pass: "0000",
},
];
//1: Matching whole object
const isEqual = (user, item) => {
return Object.entries(user).every(([key, value]) => item[key] === value);
};

let result = data.filter((item) => {
return isEqual({ role: "user", pass: "0000" }, item);
});
console.log(result);
// 2: Matching values
const isEqua2 = (user, item) =>
user.role === item.role && user.pass === item.pass;

let result2 = data.filter((item) => {
return isEqua2({ role: "user", pass: "0000" }, item);
});

console.log(result2);

How to check if object within object exists

It can be done simply using the code below:

var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal

A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.



Related Topics



Leave a reply



Submit