DEV Community

Cover image for Javascript Methods for Working with Objects {}
Tosh
Tosh

Posted on

Javascript Methods for Working with Objects {}

Objects are a very commonly used data type in which data is stored using key value pairs. To create an object you can do the following. In the example below we create a beer object with key value pairs for name, ABV, and price. There are multiple ways to instantiate an object as shown below.


let beer = { name: 'Hopadillo', ABV: '6.6%', price: '$2.00' }

// OR 

let beer = new Object({ name: 'Hopadillo', ABV: '6.6%', price: '$2.00' })

// OR 

function alcohol(name, ABV, price){
  this.name = name;
  this.ABV = ABV;
  this.price = price;
}

let beer = new alcohol('Hopadillo', 'red', '6.6%', '$2.00')

// OR 

class Alcohol {
  constructor(name, ABV, price) {
    this.name = name;
    this.maker =  maker;
    this.engine = engine;
  }
}

let beer = new Alcohol('Hopadillo', '6.6%', '$2.00');
Enter fullscreen mode Exit fullscreen mode

1. Object.keys()

This method gets all the keys of an object and puts them in an array. Here is an example using our beer object:

let beerKeys = Object.keys(beer)

// console.log(beerKeys) 
// ["name", "ABV", "price"]
Enter fullscreen mode Exit fullscreen mode

2. Object.values()

This method gets all the values of an object and puts them in an array. Here is an example using our beer object:

let beerValues = Object.values(beer)

// console.log(beerValues)
// ["Hopadillo", "6.6%", "$2.00"]
Enter fullscreen mode Exit fullscreen mode

3. Object.entries()

Object.entries() creates a new nested array with each key value pair being converted into an array.

let beerEntries = Object.entries(beer)

// console.log(beerEntries)
// [
//   ['name', 'Hopadillo'], 
//   ['ABV', '6.6%'], 
//   ['price': '$2.00']
// ]
Enter fullscreen mode Exit fullscreen mode

4. Object.fromEntries()

Object.fromEntries() is used to convert an array into an object. It’s basically the opposite of Object.entries().

let beer = [
  ['name', 'Hopadillo'], 
  ['ABV', '6.6%'], 
  ['price', '$2.00']
]

let beerFromEntries = Object.fromEntries(beer)

// console.log(beerFromEntries)
// {
//   name:"Hopadillo",
//   ABV:"6.6%",
//   price:"$2.00"
// }
Enter fullscreen mode Exit fullscreen mode

5. Object.assign()

Object.assign() is used to merge multiple objects into one object.

let beer = { name: 'Hopadillo', ABV: '6.6%', price: '$2.00' }
let beerBreweryLocation = { state: 'Texas' }

let beerObj = Object.assign(beer, beerBreweryLocation)

// console.log(beerObj)
// {
//   name:"Hopadillo",
//   ABV:"6.6%",
//   price:"$2.00",
//   state:"Texas"
// }
Enter fullscreen mode Exit fullscreen mode

There are of course other methods that you can use on objects, but you likely won’t run into them in the wild too often. To see a more extensive list of methods that can be used on objects check out MDN.
If you found this article helpful check out my open source livestreaming project ohmystream.

Top comments (0)