Find object by id in an array of JavaScript objects

Use the find() method: myArray.find(x => x.id === ’45’).foo; From MDN: The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned. If you want to find its index instead, use findIndex(): myArray.findIndex(x => x.id === ’45’); From MDN: The findIndex() … Read more

Length of a JavaScript object

Updated answer Here’s an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes: var size = Object.keys(myObj).length; This doesn’t have to modify any existing prototype since Object.keys() is now built-in. Edit: Objects can have … Read more

How can I merge properties of two JavaScript objects dynamically?

ECMAScript 2018 Standard Method You would use object spread: let merged = {…obj1, …obj2}; merged is now the union of obj1 and obj2. Properties in obj2 will overwrite those in obj1. /** There’s no limit to the number of objects you can merge. * Later properties overwrite earlier properties with the same name. */ const … Read more

How can I check if an object is an array? [duplicate]

The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype. if(Object.prototype.toString.call(someVar) === ‘[object Array]’) { alert(‘Array!’); } Or you could use typeof to test if it is a string: if(typeof someVar === ‘string’) { someVar = [someVar]; } Or if you’re not concerned about … Read more

How do I correctly clone a JavaScript object?

2022 update There’s a new JS standard called structured cloning. It works on all browsers: const clone = structuredClone(object); Old answer To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object’s prototype that should be left in … Read more

How do I test for an empty JavaScript object?

ECMA 5+: // because Object.keys(new Date()).length === 0; // we have to do some additional check obj // 👈 null and undefined check && Object.keys(obj).length === 0 && Object.getPrototypeOf(obj) === Object.prototype Note, though, that this creates an unnecessary array (the return value of keys). Pre-ECMA 5: function isEmpty(obj) { for(var prop in obj) { if(Object.prototype.hasOwnProperty.call(obj, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)