1. Delete 1 property of 1 Object
1 2 3 4 5 6 | let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; |
There are many ways to delete an object property as above
1 2 3 4 5 6 7 | delete myObject.regex; // or, delete myObject['regex']; // or, const prop = "regex"; delete myObject[prop]; |
2. Check if the Object has that key or not?
The uncertainty test is not the correct way to check if a key exists or not. What if the key exists but the value is undefined?
1 2 3 | let obj = { key: undefined }; obj["key"] !== undefined // false, but the key exists! |
There are also many ways that an exact test can be done
The first can be mentioned is the print operator, remember to use parentheses otherwise it will error
1 2 | "key" in obj // true, regardless of the actual value |
1 2 3 | !("key" in obj) // true if "key" doesn't exist in object !"key" in obj // ERROR! Equivalent to "false in obj" |
Or you can use hasOwnProperty
1 2 | obj.hasOwnProperty("key") // true |
3. Size of an Object
The most likely answer would be
1 2 3 4 5 6 7 8 9 10 11 | Object.size = function(obj) { let size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object const myObj = {} let size = Object.size(myObj); |
This is an update as of 2016 and widely deployed ES5 and above. For IE9 + and all other modern ES5 + supported browsers, you can use Object.keys () to make the code above become:
1 2 | let size = Object.keys(myObj).length; |
This does not have to modify any existing prototypes as Object.keys () is now built-in. Objects can have symbolic properties that cannot be returned through the Object.key method. Therefore, the answer would be incomplete without mentioning them. Symbol types have been added to the language to create unique identifiers for object properties. The main benefit of symbol type is to prevent overwriting.
Object.keys or Object.getOwnPropertyNames do not work with the symbol property. To return them you need to use Object.getOwnPropertySymbols.
1 2 3 4 5 6 7 8 9 10 11 12 | let person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 |
4. Conditionally add properties to the object?
To add properties to an object depending on conditions, we can use the following
1 2 3 4 5 6 7 | const someObj = { prop3: 'Arsenal!' }; const obj = { prop1: "value1", prop2: "value2", ...(someObj ?? {}) } |
The same can be used with the React component
1 2 3 4 5 6 | <MyComponent prop1="value1" prop2="value2" ...(someObj ?? {}) /> |