object
An object is just a collection of properties that have values.
Objects can be represented as key-value pairs that are separated with a comma.
The key represents the property name and is always a string.
The value can be anything
Objects are great when you want to share unchanging structured key-value data.
Objects are not appropriate for dynamic information that is updated frequently or unknown until runtime.
Objects are not appropriate for storing data that is continuously updated, changed or sorted.
Key-Value Pairs
An object can be thought of as a list of key-value pairs.
const myObject1 = {
key1: 'stringValue1',
key2: 'stringValue2'
}
const myObject2 = {
key1: 10,
key2: 20,
key3: 'stringValue3'
}
const myColors = {
red: '#####',
blue: '#####',
myColors.red
myColors['red']
const myObject3 = { name:"Monday", value:42.5 };
Creating
const myObject1 = {}; // constructor shortcut
const myObject2 = new Object();
Updating
Object.assign lets you update a key-value object with keys and values from a second key-value object.
const defaults = {
author: "",
title: "",
year: 2019,
rating: null,
};
const book = {
author: "Steve Smith",
title: "Learn JavaScript",
};
const newObject = Object.assign( {}, defaults, book };
const newObject = { ...defaults, ...book };
Square Brackets
When you are reading from an object you need to use square brackets
var myValues = myObject3["name"] + "day";
You can use square brackets to add or update properties
myObject3["name"] = "Tuesday";
myObject3["anothernewproperty"] = "some text";
Object.keys
Returns an array of the keys (or property names)
const myArrayOfKeys = Object.keys(myObject2);
Object.values
Returns an array of the values
const myArrayOfValues = Object.values(myObject2);
Object.entries
Returns an array of [key, value] pairs.
for (const [key, value] of Object.entries(myObject2)) {
console.log( "Key is " + key + " and Value is " + value);
}
Iterating over Objects
After ES 2015
Before ES 2015
You can use the for-in loop
you only have access to the object's key.
when using this you need to check if the property belongs to the object
for (var property in myObject) {
if (myObject.hasOwnProperty(property)) {
}
}
Adding default properties
keep your objects flat, no nested objects
If you add a value with the same key, it will use whatever value is declared last.
After ES 2009
const myDefault = { prop1: "", prop2: 'london', prop3: null, prop4: 20 }
const myObject = { prop1: 'Simon', prop4: 30 }
const myNewObject = Object.assign( {}, myDefaults, myObjects);
After ES 2015
using the spread operator which returns the key-values as a list.
const myNewObject = Object.assign(...myDefaults, ...myObjects);
const myNewObject = Object.assign(...myDefaults, prop4: 30 ); // for a single property
Retrieve unique values from an array of objects
const myArrayOfObjects = [
{ prop1: 'value1', prop2: 'value2' },
{ prop1: 'value3', prop2: 'value4' },
{ prop1: 'value3', prop2: 'value5' }
]
const myUniqueValues = [...myArrayOfObjects.reduce( ( myprops , { prop1 } ) => myprops.add(prop1), new Set() ) ];
delete keyword
The delete keyword can only be used to remove something from an object
You cannot delete variables or whole objects.
If you are not in strict mode trying to delete variables or objects does not generate an error, it just gets ignored.
Deconstructing
Similar to array deconstructing except curly brackets are used instead of square brackets.
var { VariableName1, VariableName2 } = myObject
instanceOf operator
Evaluates to true if the object inherits from a class's prototype
class MyClass { }
let x = new MyClass();
x instanceof MyClass // true
Object Wrappers
It is possible to work with the value data types (string, number, boolean, symbol) as if they were objects.
Everytime you use a method or property on a value data type a special temporary object wrapper is created to perform the operation and is then automatically destroyed afterwards.
These object wrappers have the names String, Number, Boolean and Symbol.
It is possible to create these object wrappers directly using the new keyword but this is not recommended.
When a variable is declared with the keyword 'new', the variable is created as an object.
var a = new string()
var a = new String() ??
var b = new number()
var c = new boolean()
Convert an Object to Array
Using the spread operator
const myObject = {
prop1: 'value1',
prop2: 'value2';
};
const myArray = [...myObject]
// [[ 'prop1', 'value1' ] , [ 'prop2','value2' ] ]
Convert an Object to String
Using chaining and template strings
function objectToString(myObject) {
const theresult = [...myObject]
.sort(mySortFunction)
.map( ( [key,value] ) = > {
return `${key}:${value}`;
})
.join(',');
result theresult;
}
// "prop1:value1, prop2:value2"
Spread Operator
The object spread operator is symbolized with three dots ( ... )
We can use it to combine two objects to make one larger object.
var myObject1 = {
property1: "Monday",
property2: "Tuesday"
}
var myObject2 = "Wednesday"
var myCombinedObject = {
…myObject1,
myObject2
}
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext