简体   繁体   中英

lodash indexBy with not uniq keys

How I can index array with not uniq keys. I try use lodash indexBy, but it gives not expected result.

var keys = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'left', 'code': 100 },
  { 'dir': 'right', 'code': 50 },
  { 'dir': 'right', 'code': 51 }
];
var a = _.indexBy(keys, 'dir');

Result:

{ left: { dir: 'left', code: 100 },
  right: { dir: 'right', code: 51 } }

Expected result:

{ left: [{ dir: 'left', code: 100 }, { 'dir': 'left', 'code': 97 }],
  right: [{ dir: 'right', code: 51 }, { 'dir': 'right', 'code': 50 }] }

You need to use _.groupBy for that, like this

console.log(_.groupBy(keys, 'dir'));

would print

{ left: [ { dir: 'left', code: 97 }, { dir: 'left', code: 100 } ],
  right: [ { dir: 'right', code: 50 }, { dir: 'right', code: 51 } ] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM