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's photo

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's photo

yes. A good answer drift boss

Marco Alka's photo

Software Engineer, Technical Consultant & Mentor

In addition to @lichtjaeger 's anwer, you can go for for .. of, which is a new loop in ES6:

The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.


Difference between for...of and for...in

The for...in loop will iterate over all enumerable properties of an object.

The for...of syntax is specific to collections, rather than all objects. It will iterate in this manner over the elements of any collection that has a [Symbol.iterator] property.

The following example shows the difference between a for...of loop and a for...in loop.

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's photo

Very good! thank you. wordle

Phil Reacher's photo

We paperwritingservices.reviews can help you write a good quality essay of any level of complexity

Thomas Frank's photo

I just started learning Javascript a month ago and don't have enough experience to handle your problem. quordle

Ch Azeem Sattar's photo

I am Website Developer

hlo the articl is very intersting