var arr = _.map(obj)
You can use _.map
function (of both lodash
and underscore
) with object
as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)
) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.
Example:
var obj = {_x000D_
key1: {id: 1, name: 'A'},_x000D_
key2: {id: 2, name: 'B'},_x000D_
key3: {id: 3, name: 'C'}_x000D_
};_x000D_
_x000D_
var array1 = _.map(obj, v=>v);_x000D_
console.log('Array 1: ', array1);_x000D_
_x000D_
/*Actually you don't need the callback v=>v if you_x000D_
are not transforming anything in between, v=>v is default*/_x000D_
_x000D_
//SO simply you can use_x000D_
var array2 = _.map(obj);_x000D_
console.log('Array 2: ', array2);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}
) with additional argument in map
and then use it how you want.
However there are other Vanilla JS solution to this (as every lodash
solution there should pure JS version of it) like:
Object.keys
and then map
them to valuesObject.values
(in ES-2017)Object.entries
and then map
each key/value pairs (in ES-2017)for...in
loop and use each keys for feting valuesAnd a lot more. But since this question is for lodash
(and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.
There are other lodash solutions like _.values
(more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys
or transforming values a bit, then the best solution is to use a single _.map
as addresed in this answer. That will bt not that difficult as per readability also.