sambomartin sambomartin - 7 days ago 7
Javascript Question

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

Answer

You can use lodash's _.map():

var obj = { 
  prop1 : "value",
  prop2: { sub:1}
};

var result = _.map(obj, function(value, prop) {
  return { prop: prop, value: 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 ES6:

const obj = { 
  prop1 : "value",
  prop2: { sub:1}
};

const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));

console.log(result);

Comments