lodash - project/transform object into key value array

天大地大妈咪最大 提交于 2019-11-28 07:26:27

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

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});
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!