An Interest In:
Web News this Week
- March 22, 2024
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
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');
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"]
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"]
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']// ]
4. Object.fromEntries()
Object.fromEntries() is used to convert an array into an object. Its 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"// }
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"// }
There are of course other methods that you can use on objects, but you likely wont 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.
Original Link: https://dev.to/toshvelaga/javascript-methods-for-working-with-objects--j4j
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To