Adding a specific object with array value in Angular: A step-by-step guide

My list

let myList=["item1","item2"];

Want to insert the object in this format

let myFinalList=[["item1":{"value1":"XXX","value2":"YYY"}],["item2":{"value1":"XXX","value2":"YYY"}]];

Any suggestions on how to achieve this using Angular?

Answer №1

There are various methods to accomplish this task. Could you provide more details about the specific requirement? Does the object structure need to be consistent for all elements in the array?

Building on your description, it seems that the desired output has a particular structure:

{
  "test1": { "val1":"XXX", "val2":"YYY" },
  "test2": { "val1":"XXX", "val2":"YYY" }
}

You may consider using Array#reduce along with the spread operator to transform the array accordingly:

let myArr = ["test1", "test2"];

const output = myArr.reduce((acc, curr) => ({
  ...acc,
  [curr]: { val1: "XXX", val2: "YYY" }
}), Object.create(null));

console.log(output);

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

Struggling to navigate through an Angular form to reach its controls

Introduction: I am facing a challenge with nested angular forms that seems simple but is proving to be difficult. The dynamic creation of formGroups and formArrays within multiple components is causing confusion. I apologize for the lengthy code snippet, ...

Enhance Your SVG Elements with Angular Tooltips

I am faced with a challenge on my website where I have an SVG element: <ellipse id="svg_2" cy="78.999999" cx="1042.499999" stroke-width="1.5" stroke="#000" fill="#fff"/> My goal is to add a tooltip to this specific element. I attempted using NGPrim ...

Angular 7: Efficiently Implementing Multiple Cascading Combobox Components

My component is designed to handle the management of cascading countries and states. When I input only one country and state in the form, everything functions perfectly. However, if I input three countries and states, the system malfunctions as shown in th ...

Tips for comparing and finding the variance between two multidimensional arrays in PHP

Looking for assistance with a coding problem. I am working with two arrays, arr1 and arr2 <?php $arr1[0]['name'] = "Ben"; $arr1[0]['level'] = "3"; $arr1[0]['age'] = "10"; $arr1[0]['gender'] = "M"; $arr1[1][&apos ...

Does anyone know why extend() and append() methods in Python return None instead of a value?

My opinion is that when using list1.extend(list2) and list1.append(num), the mutated list and mutating id should be returned instead of returning None. ...

Tips for handling changing form information with useState?

I am faced with a dilemma - I have a dynamic form with potentially hundreds of input fields, making it impractical to create a state for each one individually. My plan is to use an object with the unique key of each form field, but I could use some guidanc ...

Tips for incorporating the closeAutocomplete function into ng4-geoautocomplete

Hey there! I've incorporated the ng4-autocomplete component into my custom component and now I'm trying to figure out how to detect when the autocomplete dropdown closes. Can you help me out with implementing the "closeAutocomplete" method? Let& ...

Dealing with AOT challenges when integrating ng2-bootstrap into Angular 2 applications

I'm currently developing an Angular 2 app and encountering an error when attempting to create a bundle with AOT compilation following the guidelines in Angular 2 documentation here. The dependency error I'm facing is as follows: Refer to this ...

delete the contents of the Array object dictionary on iOS where the values are null

I have a Json object with the following structure: { CO = 1; CUABR = "<null>"; CUNO = "<null>"; DIV = 2; DLDAT = 1020923; SALID = "<null>"; "form_number" = MM23000; type = VHNO; }, { CO = 1; CU ...

Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code: import next from 'next'; import express from 'express'; import compression from 'compression'; import bodyParser ...

Cython offers a solution for initializing unsigned char arrays with values of 0, as Cython's Python functions and methods do not support this functionality in the traditional def __init__() method

Hi there! I encountered an issue with my Cython code that involves an unsigned char array called a, containing unsigned integers. The problem arises when passing this array into a Python method declared with def, as the values of indices after the one cont ...

assigning state to a React component by utilizing onClick event in a functional component with TypeScript

const Navigation = () => { const [activeItem, setActiveItem] = useState<string>("tasks"); return { <NavigationContainer> <NavItem onClick=(() => setActiveItem("settings")/> ...

Ways to invoke a function in Angular2 when the Boolean condition is met

Within my component class, I have implemented a popup function along with a Boolean flag that returns true or false based on specified conditions. In the template class, I want the popup function to be triggered when the flag becomes true, displaying a pop ...

Is it possible to obtain Literal types for object keys dynamically in typescript?

I am looking to extract the type of object keys. Below is a generic function for objects with keys as strings: type GenericInput = { [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, err ...

Tips for preventing the "Too many re-renders" error in React and avoiding infinite loops

While utilizing react typescript, redux toolkit, and material UI together, I encountered an error when calling the API: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. at renderWithHooks () at mountIndeterminat ...

What is the best way to insert a placeholder React element into a different Component using TypeScript?

I've encountered a Typescript error that has me stumped. Check out the code snippet below: interface AppProps { Component: JSX.ElementClass; pageProps: JSX.ElementAttributesProperty; } const App = ({ Component, pageProps }: AppProps) => { co ...

What methods can I use to organize and visualize this qualitative data in a chart?

I have a dataset that I want to represent on a line chart. The data appears as follows: [ { date: 1, depth: 1, river: 'trent', }, { date: 1, depth: 7, river: &apo ...

Chai-as-promised avoids errors in TypeScript test cases

I am attempting to utilize chai-as-promised in my Mocha test for some TypeScript code, but I am having trouble with the syntax. To troubleshoot, I set up a minimal reproducer: index.ts // Sample promise that resolves on red, fails on other values export co ...

The mysterious error of the Codeigniter Index Unknown

I need assistance with optimizing my PHP code. I have a function foo that returns an array with specific structure, and I'm unsure about the indexing in the foreach loop for accessing each ListingId. Objective: I want to iterate through the array us ...

Removing an element from the array stored in NGRX

I currently have an object stored in a repository in the following format: export interface Referential { id: string; values: Array<ReferentialData>; } export interface ReferentialData { libelle: string; value: string; borderColor: string; ...