Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written:

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country})));

The output that I am currently getting is:

{1: "Germany", 2: "Austria", 3: "Switzerland"}

I want to include the population in the output as well. When I try to modify the code, it results in a syntax error:

let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country, x.population})));

The desired output should resemble the following:

{
  "1": {
    "country": "Germany",
    "population": 83623528
  },
  "2": {
    "country": "Austria",
    "population": 8975552
  },
  "3": {
    "country": "Switzerland",
    "population": 8616571
  }
}

Answer №1

It seems like you might be looking for something along the lines of this:

const info = [
  {id: 1, category: 'Fruits', quantity: 200},
  {id: 2, category: 'Vegetables', quantity: 100},
  {id: 3, category: 'Grains', quantity: 300}
];

const dataMap = Object.fromEntries(info.map(item => [item.id, {category: item.category, quantity: item.quantity}]));

console.log(dataMap);

Answer №2

If you want to keep both country and population values as an object, you can try using Object.fromEntries:

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest}) => ([id, rest]) ));

console.log(dictionary);

If you prefer to return an array without keys:

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest}) => ([id, Object.values(rest)]) ));

console.log(dictionary);

Answer №3

You're on the right track, but to complete this task you need to create an object for the id and utilize the rest parameter.

let info = [
  {id: 1, country: 'France', population: 65273578},
  {id: 2, country: 'Italy', population: 60783755},
  {id: 3, country: 'Spain', population: 46704314}
];

let dataMap = Object.assign({}, ...info.map(({
  id,
  ...remaining
}) => ({
  [id]: remaining
})));

console.log(dataMap)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can two writable stores in Svelte be set up to subscribe to each other simultaneously?

There is a unique scenario where two objects share data, yet have different structures. For instance, the 'Team' object has the team ID as its key. The 'Team' object includes 'name' and 'users' objects as its values ...

Creating a custom function that targets a specific element

When working with JavaScript, you may often encounter functions written in the form of document.getElementById("element").someFunction(); or $("element").someFunction(); rather than the traditional someFunction($("element"));. This is similar to a function ...

What could be causing the content in my select box to change only when additional select boxes are introduced?

When working with a form in next.js and using select boxes from material UI, I encountered an issue. The number of select boxes should change based on user input, but when I modify the value inside a select box, the displayed text does not update until I a ...

Display a pop-up when hovering over a layer with react-leaflet

I am attempting to display a popup when hovering over a layer in react leaflet. Utilizing GeoJson to render all layers on the map and onEachFeature() to trigger the popup on hover, I encountered an issue where the popup only appeared upon click, not hover. ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

There seems to be an issue with node.js - headers cannot be set after they have already been sent to

As I work on developing my blog, I've encountered an issue with rendering different paths using the router parameter. Each time I attempt to display another route, an error surfaces. Unfortunately, I'm unable to provide more details at this momen ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

selection menu and advancement gauge

While working on my code, I have a task where I need to make the progress bar move a specific amount when a name is clicked based on the option's value. <!DOCTYPE html> <html> <head> <title>testinggg</title> &l ...

"Encountered an issue: Error occurred while attempting to synchronize Protractor with the page" during the execution of Protractor tests

I am facing an issue while running Protractor tests on a web application that includes both Angular and non-angular elements. Here is the structure of my code: describe("Test Name", function() { it("Test case", function() { // starting with steps on ...

Utilize AJAX to retrieve the output of a PHP randomizer

Current situation: I have a PHP file with a randomizer function and HTML that utilizes this function to display strings from a separate text document. The Function: <?php function rand_line($fileName, $maxLineLength = 4096) { $handle = @fopen($fileN ...

Vue + TypeScript prop type issue: "'Foo' is intended as a type, but is being treated as a value in this context."

As a newcomer to TypeScript and the Vue Composition API, I encountered an error that left me puzzled: I have a component that requires an api variable as a prop, which should be of type AxiosInstance: export default defineComponent({ props: { api: A ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

I am unable to add a new property to the request object in the Express framework

My goal is to add a new property to the request object in typescript. Here's the code snippet I'm using: import { request, Request, response, Response } from "express"; ((req: Request, res: Response) => { console.log(req.user); ...

What strategies can I use to steer clear of the pyramid of doom when using chains in fp-ts?

There are times when I encounter a scenario where I must perform multiple operations in sequence. If each operation relies solely on data from the previous step, then it's simple with something like pipe(startingData, TE.chain(op1), TE.chain(op2), TE. ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Tips for translating an HTML webpage from Arabic to English

I have a bootstrap site with HTML pages but no backend functionality. How can I manually translate from Arabic to English, given that I already have the translations for all content and don't need to rely on translation tools? Is there a way to map Ar ...

javascript strange behavior

I am facing an issue with my code that is attempting to display images based on their height. Strangely, the code seems to work fine when I test it with 2 images, but fails when trying with 3 or more. Check out the site: Upon clicking a menu button, the ...

Developing a TypeScript library for versatile features across multiple projects

My goal is to export multiple classes, some independent and others interdependent, encapsulated within a single namespace, in the form of a module for external project utilization. To achieve this, I have configured a webpack build to compile these classe ...