my-idlers/node_modules/collect.js/docs/api/keyBy.md
cp6 fd22b0bf58 V2 (Laravel re-make)
V2 (Laravel re-make)
2022-03-06 02:02:12 +11:00

1.1 KiB

keyBy()

The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:

const collection = collect([
  {
    product: 'Chair',
    manufacturer: 'IKEA',
  },
  {
    product: 'Desk',
    manufacturer: 'IKEA',
  },
  {
    product: 'Chair',
    manufacturer: 'Herman Miller',
  },
]);

const keyed = collection.keyBy('manufacturer');

keyed.all();

// {
//   IKEA: {
//     product: 'Desk',
//     manufacturer: 'IKEA',
//   },
//   'Herman Miller': {
//     product: 'Chair',
//     manufacturer: 'Herman Miller',
//   },
// }

You may also pass a callback to the method. The callback should return the value to key the collection by:

const upperCased = collection.keyBy(item => item.manufacturer.toUpperCase());

upperCased.all();

// {
//   IKEA: {
//     product: 'Desk',
//     manufacturer: 'IKEA',
//   },
//   'HERMAN MILLER': {
//     product: 'Chair',
//     manufacturer: 'Herman Miller',
//   },
// }

View source on GitHub