Is it possible to create a nested object inside of an array?

Looking to accomplish the following:

let listOne: any = ['item1', 'item2', 'item3'];
let details: any;

// Previously, I had a loop running and 'row' was the response outputting items 
// in the listOne array

const query_for_details = `SELECT column1 FROM tableName WHERE itemId = '${row}'`;
details = await client.query(query_for_details).then((res: any) => res.rows
console.log(details)
// Output for each item in the listOne array {name1: value1, name2: value2, name3:value3}

Now, after obtaining the query output, I aim to store it in a new variable like shown below:

let listOneDetails: any = [{'item1': {'name1': 'value1', 'name2': 'value2', 'name3':'value3'}},
{'item2': {'name1': 'value1', 'name2': 'value2', 'name3':'value3'}},
{'item3': {'name1': 'value1', 'name2': 'value2', 'name3':'value3'}}]

I've looked into using a reducer, but it doesn't seem like the right fit for my scenario. Any help would be greatly appreciated!

Answer №1

Utilizing the reduce function is one approach, but allow me to provide you with the precise algorithmic solution as well.

To avoid the N+1 anti-pattern of performing one query per row, you can retrieve all rows in a single query by utilizing a

where itemId IN (<ids array>)

After gathering all the rows, it is crucial to create an index for efficient joining of rows with items (N*Log(N)). This can be achieved using a library such as lodash's indexBy, or with just 3 lines of code:

const detailsById = {};
res.rows.forEach(row => detailsById[row.itemId] = row); 
// where row.itemId is the linking element to list One items

For performing the join, you can utilize a reduce function in the following manner:

listOne.reduce((acc, itemId) => { acc[itemId] = detailsById[itemId]; return acc;} , {});

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

TypeScript - Converting into individual compiled files

Currently, I am working on a project that consists of lengthy source files. While this is advantageous for imports, it poses challenges in terms of maintenance. For instance: /main/core.ts export type Foo { ... } export interface Bar { ... } export cla ...

Issue encountered when trying to redirect after user creation on the backend

To persist a user, I use this method inside form-registrar-usuario.component: registrarUsuario(){ const role = this.route.snapshot.params["role"] if(role == "Proponedor"){ this.autorizacionService.registrarUsuario( role, thi ...

DotLottie file loading issues

While using dotlottie/react-player, webpack 4, and react 16, I encountered module parse failed errors during compilation. "@dotlottie/react-player": "^1.6.5" "webpack": "^4.44.2", "react": "16.14.0&qu ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

I aim to link a variable in a directive with a component

Each directive comes with its own functionality and specific features. It can be challenging to understand how to connect a variable from a directive to a component. This particular directive involves detecting x-axis and y-axis positions during mouse ev ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

Utilizing a function as a prop with varying parameter types in React using Typescript

I am encountering an issue while attempting to pass a function that updates state in React. VSCode is prompting me with a typing problem. The error message states Type '(value: string) => void' is not assignable to type '(value: string | ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

`The simultaneous processing of two inputs using forkJoin`

There are two input fields on my form: Street address and Zipcode. Each field emits its value on keyup as a Subject in Angular. Before calling an API endpoint with these values, I need to ensure that both the street address and zip code values are valid. ...

After version 3.1, TypeScript no longer supports callback functions as argument types

I've encountered an issue with jQuery Terminal. My d.ts file is quite large, but it's not functioning correctly. I attempted to update dependencies, leading to everything breaking. Recently, I've been unable to update TypeScript due to error ...

The type 'Observable<any>' cannot be assigned to the type 'Observable<T>'

Here is the code I am working with: import {HttpClient} from '@ngular/common/http'; private httpClient: HttpClient; do_request(method: string, url: string, ...

Tips for type guarding in TypeScript when using instanceof, which only works with classes

Looking for a way to type guard with TypeScript types without using instanceof: type Letter = 'A' | 'B'; const isLetter = (c: any): c is Letter => c instanceof Letter; // Error: 'Letter' only refers to a type, but is being ...

Locate all rows within a specified range in PostgreSQL

My database has a table called tc_fuel where all fuel-related data from GPS vehicles is stored. I am trying to calculate MPG for a whole tank, so I need to retrieve the last "Tank Usage." However, when the tank is full (at 100), sometimes the readings repe ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

The 'xxx' type does not have an index signature, so the element is implicitly assigned an 'any' type

I'm currently facing an issue with TypeScript. The error message I'm encountering is related to the following section of code: The Interface: export default interface IUser { username: string; email?: string; isActive: boolean; group: s ...

Encountering tsconfig.json issues following the integration of Tailwindcss v3 into Next.js (create-next-app --typescipt)

Upon opening my code in VS Code, I encountered the following error: Cannot find type definition file for 'accepts'. The file is in the program because: Entry point for implicit type library 'accepts' In an attempt to resolve this issue ...

Transferring information through parent-child components via onChange

I have a question regarding data binding. In my project, I have a parent component and two child components: Parent: directives: [firstChild,secondChild], template:' <first-child [showList]="showList" (emitShowList)="getShowList($event)"& ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

I encountered an error while running a basic express app with ts-node-dev: Invalid argument: A non-string value was provided to `ts.resolveTypeReferenceDirective`

Recently, I started diving into Typescript and Express. Trying to set up a basic Express app using ts-node-dev, I encountered the following error: > ./node_modules/.bin/ts-node-dev src/index.ts 16:07:40 [I ...

Is it possible to generate code snippets for TypeScript in Visual Studio 2015?

Is it possible to create a code snippet for Angular 1.x directives written in TypeScript, even though there may be some product level configuration required? I have come across similar questions discussing TypeScript snippets on Visual Studio, but the res ...