lodash – project/transform object into key value array

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);

Leave a Comment

tech