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 available to do it.
{
prop1 : "value",
prop2: { sub:1}
}
to:
[
{key: "prop1", value: "value"},
{key: "prop2", value: {sub:1}}
]
Thanks
To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.
values() method is used to return the array of the own enumerable string keyed property values of the object.
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);
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 pairs
if it fits your case:
_.pairs({ 'barney': 36, 'fred': 40 });
// → [['barney', 36], ['fred', 40]]
Ref: https://lodash.com/docs#pairs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With