Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash - project/transform object into key value array

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

like image 800
sambomartin Avatar asked Aug 19 '15 16:08

sambomartin


People also ask

How do you turn an object into an array?

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.

What does .value do in Lodash?

values() method is used to return the array of the own enumerable string keyed property values of the object.


4 Answers

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);
like image 117
Ori Drori Avatar answered Sep 24 '22 23:09

Ori Drori


You don't even need lodash for that:

var arr = Object.keys(obj).map(function(key){   return { key: key, value: obj[key] }; }); 
like image 43
Joseph Avatar answered Sep 21 '22 23:09

Joseph


A little bit of ES6 :

_.map( obj, (value, key) => ({key,value}) )

like image 21
Dzianis Sudas Avatar answered Sep 24 '22 23:09

Dzianis Sudas


You can use pairs if it fits your case:

_.pairs({ 'barney': 36, 'fred': 40 });
// → [['barney', 36], ['fred', 40]]

Ref: https://lodash.com/docs#pairs

like image 20
Skarllot Avatar answered Sep 24 '22 23:09

Skarllot