lodash - project/transform object into key value array

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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

回答1:

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

Or you can do it using ES6 array destructuring, with Shorthand property names, and Object#entries (ECMAScript 2017 Draft) or lodash's _.entries:

const obj = {    prop1 : "value",   prop2: { sub:1} };  const result = Object.entries(obj).map(([prop, value]) => ({ prop, value }));  console.log(result);


回答2:

You don't even need lodash for that:

var arr = Object.keys(obj).map(function(key){   return { key: key, value: obj[key] }; });


回答3:

A little bit of ES6 :

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



回答4:

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" //     } //   } // ]


回答5:

You can use pairs if it fits your case:

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

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



回答6:

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


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