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

Guide to asynchronously loading images with Bearer Authorization in Angular 2 using NPM

I am in search of a recent solution that utilizes Angular2 for my image list. In the template, I have the following: <div *ngFor="let myImg of myImages"> <img src="{{myImg}}" /> </div> The images are stored as an array w ...

"Angular application experiencing navigation blockage due to multiple concurrent HTTP requests using RxJS - Implementation of priority-based cancel queue

I've come across similar threads, but I have yet to find a suitable solution for my specific issue. Situation: Currently, I'm navigating on both the server side and client side simultaneously. This entails that every frontend navigation using ro ...

Dealing with a nested object problem in Angular using TypeScript

I am currently working on an Angular 15 application that is designed to showcase information about different games to users. Within the application, I have a global object structured like this: GAMES_INFO: { skyroads: { name: 'Sky Roads&a ...

Is it possible to automatically refresh a webpage with the same URL when accessed on the same server?

Is there a way to trigger a URL page refresh using JS code located on the same server? For example, I have a URL page open on multiple devices connected to the same server. How can I ensure that when I click 'Update,' the page refreshes simultan ...

Working with dynamic checkbox values in VueJS 2

In my project using VueJS 2 and Vuetify, I am creating a subscription form. The form is dynamic and fetches all the preferences related to a subscription from the server. In the example below, the preferences shown are specifically for a digital magazine s ...

Bring in a 3-dimensional model using JSONLoader in three.js

I'm facing some challenges with incorporating a simple 3D object created in Maya into my Three.js project using JSONLoader. The object consists of various materials (Lambert and Phong) and different colors. I used Maya to create a .obj file, then Ble ...

React - How to Close Material-UI Drawer from a Nested Menu

Currently, I am utilizing a fantastic example (here) to create a dynamic nested menu for my application. Taking it a step further, I am trying to integrate it into a Material UI appbar/temporary drawer. My goal is to close the drawer when the user clicks o ...

Issues with applying styles to custom components in styled-components

I attempted to customize the inner elements of react-id-swiper using the code below: import Swiper from 'react-id-swiper'; import styled from 'styled-components'; const MySwiper = ({ className, children }) => ( <Swip ...

What is the best way to add an element from a parent component to an array within a child component in a Vue 3 application?

I am in the process of transitioning from Vue's Options API to the Composition API, and as part of this transition, I have built a small Todo App. Within App.vue, my code looks like this: <template> <div id="app"> <div ...

Creating URL query parameters for a nested REST API: A step-by-step guide

I am faced with the challenge of constructing a POST request for a nested REST API (json object) dedicated to search functionality. I am unsure about how to format the URL parameters due to its complex nesting structure. How should I include question marks ...

What is the best method for transferring data from Firestore into a Vue CLI project?

I am currently facing a challenge in importing data from a Firestore Database into my Vue CLI project. Despite following multiple tutorials, I have not been successful in making it work correctly. It appears that I am encountering difficulties in retrievin ...

The extend keyword in TypeScript causing issues with type inference

Why is TypeScript showing an error in the code below? type A = { kind: "a" } type B = { kind: "b" } const a = (a: A): void => undefined const b = (b: B): void => undefined const c = <C extends A | B>(c: C): void => (c.kind == "a" ? a(c) : ...

Google Maps in Angular is not showing up

My Angular Google Maps implementation seems to be working, but unfortunately, the map is not showing on my website. I have confirmed that my JS is loading the maps and I can retrieve the map properties. Interestingly, when I check the Chrome AngularJS Debu ...

Tips for augmenting cell with additional data in react-datepicker

Is it possible to include additional text in a cell using react-datepicker? For example, similar to what is shown in this image: view image here ...

Guide on waiting for an asynchronous function in the constructor in JavaScript

In the process of creating a JS class, I encounter a situation where I need to call wasmFunc in the constructor and store its output in this.val. However, since wasmFunc comes from a WebAssembly file, it is necessary to execute an async function called loa ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

Remain on the current webpage following the submission of comparable ajax-forms

Seeking assistance with an issue involving Ajax that I believe is unique. Desired Outcome I have a newsfeed with various posts and interspersed forms, such as polls, for user interaction and submission of results. Objectives Users should be able to inter ...

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

When the Ajax "GET" request is made to the intra-service, the CMS service worker will respond with an "OK" even when offline

Hello there, We are currently utilizing an open-source CMS that recently received an upgrade with a new feature - a javascript serviceworker implementation to manage all requests. This CMS includes workflow forms where users engage (created by us). Durin ...