objects? No... array, please!
Fabio Russo
Posted on May 4, 2018
I don't like objects...that much!
This is an object:
const obj = {breed:"labrador",age:9}
But sometimes I prefer to work with arrays.
Why? Because they really look better to me... and there are really a lot of methods or loops that work just with [arrays]!
These are some tools used to "convert" objects to arrays.
//Object.values() will give you an array of all the object "values"
const obj = {breed:"labrador",age:9}
const values = Object.values(obj)
console.log(values)
//-> ["labrador", 9]
//Object.keys() will give you an array of all the object "keys"
const obj = {breed:"labrador",age:9}
const keys = Object.keys(obj)
console.log(keys)
//-> ["breed", "age"]
//Object.entries() will give you an arraysh version of the object.
//Where the key and the value will be paired into an array...
//and all of those arrays will be "pushed" into another array.
const obj = {breed:"labrador",age:9}
const entries = Object.entries(obj)
console.log(entries)
//->[["breed", "labrador"], ["age", 9]]
This is easy peasy stuff, but very often, at the beginning of my journey in JS, objects were very often a problem for me.
If only they had told me before ...
P.S: These tools are ok... if it’s ok to work with arrays instead of objects.
Sometimes you’ve to use objects... because of performance or long term maintenance.
💖 💪 🙅 🚩
Fabio Russo
Posted on May 4, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Brief Performance Analysis of Arrays and Objects through the lens of Big O Notation.
August 26, 2020