可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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}); });