Start a personal dev blog on your domain for free with Hashnode and grow your readership.
What's the best way to map over an Object/Array in JavaScript (ES6)?
Sometimes I need to map both objects properties and arrays. Since Array.map
supports only arrays, I end up using lodash/map
(Lodash supports both objects and arrays).
What's the recommended way to handle this?
Peter Scheler
JS enthusiast
Dec 1, 2016
In ES2017:
const obj = { a: 1, b: 2 } Object.entries(obj).map(([key, value]) => /* do what you want */)
ES2015:
const obj = { a: 1, b: 2 } Object.keys(obj).map(key => { const value = obj[key] /* do what you want */ })
.map
returns an Array. If you want an Object back, use.reduce
and build the Object.stewart kennedy
Feb 18, 2022
yes. A good answer drift boss
Marco Alka
Software Engineer, Technical Consultant & Mentor
Dec 1, 2016
In addition to @lichtjaeger 's anwer, you can go for
for .. of
, which is a new loop in ES6:Object.prototype.objCustom = function () {}; Array.prototype.arrCustom = function () {}; let iterable = [3, 5, 7]; iterable.foo = "hello"; for (let i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom" } for (let i of iterable) { console.log(i); // logs 3, 5, 7 }
(Source)
Mariah Carey
Sep 7, 2022
Very good! thank you. wordle
Phil Reacher
sport
Oct 9, 2022
We paperwritingservices.reviews can help you write a good quality essay of any level of complexity
Thomas Frank
Marketer
Oct 20, 2022
I just started learning Javascript a month ago and don't have enough experience to handle your problem. quordle
Ch Azeem Sattar
I am Website Developer
Dec 3, 2022
hlo the articl is very intersting