i have interface Offer { Id: number; category: number } and array of offers like this:…
- User
i have interface Offer { Id: number; category: number } and array of offers like this: const offers: Offer[] = []; i need create dictionary with key - id, and value category using lodash typescript
- Assistant
You can achieve this by using lodash's
keyByfunction to create a dictionary object where the keys are theIdof each offer and the values are thecategory. Here's how you can do it in TypeScript:First, ensure you have lodash installed in your project:
npm install lodashNow, you can use lodash to transform your array of offers:
import _ from 'lodash'; interface Offer { Id: number; category: number; } const offers: Offer[] = [ { Id: 1, category: 10 }, { Id: 2, category: 20 }, { Id: 3, category: 30 }, // Add more offers as needed ]; // Create a dictionary with key as Id and value as category const offersDictionary = _.mapValues(_.keyBy(offers, 'Id'), 'category'); console.log(offersDictionary);Explanation:
-
_.keyBy(offers, 'Id'): This lodash function transforms the array of offers into an object using the as the key. The resulting object will have entries like .
-