Object Manipulation in JavaScript
Most new JavaScript developers are pretty familiar with the different ways to work with and manipulate arrays. You have your loops and your maps and filters along with the countless other methods you can use to transform an array. I found that I was less comfortable transforming objects though. Here’s what I learned after setting out to remedy that. Hope it helps you too!
Bracket and Dot Notation
Let’s start with the basics. There are two ways to access properties of an object. Use either bracket or dot notation. Both examples return the same thing.
const claire = {name: 'Claire',age: 34,occupation: 'developer'}console.log(claire.name)//Claireconsole.log(claire['name'])//Claire
Get the Keys or Values from an Object
Use Object.keys() or Object.values() to return an array of the keys or values of an object depending on your needs.
const claire = {name: 'Claire',age: 34,occupation: 'developer'}Object.keys(claire)//[[ 'name', 'age', 'occupation' ]]Object.values(claire)//[ 'Claire', 34, 'developer' ]
Get Arrays of All the Key Value Pairs
You can use Object.entires() to return an array with arrays inside containing the key value pairs.
const claire = {name: 'Claire',age: 34,occupation: 'developer'}Object.entries(claire)//[ [ 'name', 'Claire' ], [ 'age', 34 ], [ 'occupation', 'developer' ] ]
Combine Two Objects
Use the spread operator (. . .) to combine two objects or alter an object and return a new one.
const claire = {name: 'Claire',age: 34,occupation: 'developer'}const newObject = {...claire,city: 'Brooklyn'}console.log(newObject)//{ name: 'Claire', age: 34, occupation: 'developer', city: 'Brooklyn' }
Looping Through an Object
To loop through an object you can use two different methods. The first example uses a for loop and Object.entries() like so:
const claire = {name: 'Claire',age: 34,occupation: 'developer'}for (const [key, value] of Object.entries(claire)) {console.log(`${key}: ${value}`)//name: Claire//age: 34//occupation: developer}
You can also use for . . . in like this:
//see claire object declared abovefor (const key in claire) {console.log(`${key}: ${claire[key]}`)// name: Claire// age: 34// occupation: developer}