I\'m about to use forOwn
to iterate through an object\'s properties and create an array manually and can\'t helping thinking there\'s a oneliner already availab
You can use pairs
if it fits your case:
_.pairs({ 'barney': 36, 'fred': 40 });
// → [['barney', 36], ['fred', 40]]
Ref: https://lodash.com/docs#pairs
In response to Ori's comment and for completeness, I've posted the _.forOwn version. It's marginally faster but you need to declare the array first (not-a-one-liner).
var arr = [];
_.forOwn(obj,function(item, key) {
arr.push({ property : key, value : item});
});
If you are using lodash/fp you can use _.entries
const a = { one: 123, two: { value: 'b' }};
const pairs = _.entries(a).map(p => ({ key:p[0], value: p[1] }))
console.log(pairs)
// [
// {
// "key": "one",
// "value": 123
// },
// {
// "key": "two",
// "value": {
// "value": "b"
// }
// }
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-fp/4.15.0/lodash-fp.js"></script>
You don't even need lodash for that:
var arr = Object.keys(obj).map(function(key){
return { key: key, value: obj[key] };
});
A little bit of ES6 :
_.map( obj, (value, key) => ({key,value}) )
You can use lodash's _.map() with shorthand property names:
const obj = {
prop1 : "value",
prop2: { sub:1}
};
const result = _.map(obj, (value, prop) => ({ prop, value }));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
Or you can do it using Object#entries with Array.map() and array destructuring:
const obj = {
prop1 : "value",
prop2: { sub:1}
};
const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));
console.log(result);