checking if an element is an object in javascript [duplicate] - javascript

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Closed 1 year ago.
I am using the following code to check if an element is an object in javascript:
element.constructor == Object Is this a correct way or there are more appropriate ways
to check that? An alternate would be to use this - typeof element === 'object'
There seem to be multiple ways to do that not sure which one is more appropriate

It would be the easiest if you use the lodash package. Lodash is quite common in the js community and I really can recommend this in most cases.
A modern JavaScript utility library delivering modularity, performance & extras.
Lodash docs of isObject function: https://lodash.com/docs/4.17.15#isObject
Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
Example
_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(_.noop);
// => true
_.isObject(null);
// => false

Related

Does array include object with specific key? [duplicate]

This question already has answers here:
Check if array of objects contain certain key
(6 answers)
Closed 5 months ago.
I need to find out if an array of a JS object includes an object with a specific key.
I am using,
my_array.filter((e) => Object.keys(e).includes(my_key)).length > 0
but there must be a way to do it simpler.
Any suggestions in addition to Check if array of objects contain certain key ?
Instead of .filter(…).length > 0, use .some(…).
Instead of Object.keys(…).includes(…), use … in … (or Object.hasOwn(…, …) if you need to ignore inherited properties).
So
my_array.some(e => my_key in e)
instead of filter use some, already returns true or false and it shortcircuits as soon as it finds the first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

what is at() method in JavaScript? [duplicate]

This question already has answers here:
Using Array.at(index) instead of Array[index] in JavaScript
(4 answers)
Closed last year.
Array.prototype.at()
what is .at() method in JavaScript?
const myList = ['index0', 'index1', 'index2']
myList.at(1) // 'index1'
mylist.at(-1) // 'index2'
there are many methods in js that similarly do this, why using this new method?
Yes, there are similar ways to get an element from an array or string, but at() will use a clear and easy syntax to get this.
give an index and return value
the principle is easy, just put your desire index and get value, if there isn't a value at this index, it returns undefined
for examples:
const myList = ['index0', 'index1', 'index2']
// to get latest item in the list using common ways:
const latestItem = myList[ myList.length - 1]
// using simpler approach with at()
const latestItem = myList.at(-1)
similarly, at() method will work fine with strings.
at the writing time of this post, at() will not be supported by some browser, you can find this here.
you can use polyfill if you want to use at() method in your codebase.

How to Access Javascript object property if only that property is available - ReactJS [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 3 years ago.
I need to access Javascript object property if and if only that property is available.
object.property.anotherInnerProperty ="value"
To access and check above value we normally use following way
if(object && object.property && object.property.anotherInnerProperty=="value")
then do this
Is there any effective and less code method to access object.property.anotherInnerProperty ?
You can use optional chaining to make your code less verbose:
if(object?.property?.anotherInnerProperty === "value") {
// then do this
}
Note that this is still a new feature of the language, so you might need some transpiling to make it work in most of the browsers.
You can also use lodash.get method:
const object = {
property: {
innerProperty: 'foo'
}
};
const anotherObject = null;
console.log(_.get(object, 'property.innerProperty'));
console.log(_.get(anotherObject, 'property.innerProperty'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Is there something like object.toJSON in ES6? [duplicate]

This question already has answers here:
Convert JS object to JSON string
(23 answers)
Closed 7 years ago.
I'm using ES6 I transpile using Babel into ordinary JavaScript.
I want to serialise objects into JSON format and am wondering if ES5,ES6 offers a convenient function to do so.
For Maps and Sets there is a toJSON()-function proposed in ES7
You can use JSON.stringify and pass any kind of variable to it (given that it can be represented in JSON).
It works in all current browsers; in case you need a fallback for a really old browser, you can use Crockford's JSON-js.
However, keep in mind that, regarding objects, only public properties are serialized. There's no a generic way to serialize function variables etc. on the fly.
This is why some special object types provide a toJSON or similar method. In order to use such a function for arbitrary objects, you must pass a function as second parameter to JSON.stringify which checks for the existence of a toJSON function.
For example, the following should work (not tested, just from the top of my mind):
var jsonString = JSON.stringify(someLargeObject, function(key, value){
return (value && typeof value.toJSON === 'function')
? value.toJSON()
: JSON.stringify(value);
});
If your someLargeObject contains a sub-object with a toJSON method, this code would use the object's implementation, otherwise use JSON.stringify.

Optimal way of determining array type [duplicate]

This question already has answers here:
JavaScript way to tell if an object is an Array [duplicate]
(6 answers)
Closed 7 years ago.
What is the best way to determining the object type is Array and why?.
var arr = [];
// Method #1
Array.isArray(arr);
// Method #2
toString.call(arr) == "[object Array]"
// Method #3
arr.constructor == Array
All three methods can be used to test if variable is of Array type. However, there are some nuances. I will start from the last to first.
Method #3. Will not work if variable in question came from other winndow/frame. In this case, constructor will point the the different Array object and this check will return false. For the same reason, arr instanceof Array is not bullet-proof. So it's not 100% reliable.
Method #2. This is the method that has been traditionally used to verify array type. In fact, Array.isArray polyfill is based on this method. The only disadvantage is that it's cumbersome and verbose.
Method #1. Is the one from ES5 that should finally be used to test array type, no matter what realm array comes from (like iframe). This is is the best in the list.
The prefered method is to use Array.isArray. This is present in the ES5 language specification and quite well supported by the browsers.
If you plan to support old browsers, You can find a polyfill on MDN. The polyfill is basically your second option.
The last option will not work if you play with iframes.
var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false
The reason is that the Array constructor is diffferent for each window object. Using this to detect arrays will work 99% of the time but will suddenly fail one day.

Categories