Transforming an array of JSON items into a unified object using Angular

I need to convert an array list into a single object with specific values using TypeScript in Angular 8. Here is the array:

"arrayList": [{
    "name": "Testname1",
    "value": "abc"
  },
  {
    "name": "Testname2",
    "value": "xyz"
  }
]

The desired format for conversion is as follows:

data: {
  "Testname1": "abc",
  "Testname2": "xyz",
}

Despite my efforts, I keep ending up with a list instead of a single object. Any assistance with achieving the desired outcome would be greatly appreciated.

Answer №1

Here is an example of how you can achieve this:

 
var array =  [
            {
                "title": "Title1",
                "content": "example1"
            },
            {
                "title": "Title2",
                "content": "example2"
            }
           ];

var finalResult = {};
for (var index = 0; index < array.length; index++) {
  finalResult[array[index].title] = array[index].content;
}

console.log(finalResult);

Answer №2

Experiment by utilizing the .reduce() method in the following manner:

const itemsArray = [{ "item": "Item1", "price": "$10" }, { "item": "Item2", "price": "$20" }];

const result = itemsArray.reduce((total, {item, price}) => {
  total[item] = price;
  return total;
}, {});

const finalResult = { result };

console.log(finalResult);

Answer №3

Transform a list of [name, value] entries using Array.map() and then convert it into an object with Object.fromEntries():

const arrayList = [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" }];

const result = Object.fromEntries(arrayList.map(({ name, value }) => [name, value]));

console.log(result);

Answer №4

Kindly utilize the following code snippet

const initialData = {
  "listItems": [{
      "name": "Item1",
      "id": 123
    },
    {
      "name": "Item2",
      "id": 456
    }
  ]
};

const modifiedData = {
  updated: {}
};

for (const element of initialData["listItems"]) {
  modifiedData.updated[element.name] = element.id;
}

console.log(modifiedData);

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

Error: Pointer array causing Segmentation Fault

What is causing the Segmentation Fault error to occur? Despite my efforts to document thoroughly, I have been unable to pinpoint the exact reason. char * sir=malloc(50*sizeof(char)); char * aux; int i; for(i=1;;i++) { fgets(aux, 50, stdin); if(s ...

How can I restrict the return type of a generic method in TypeScript based on the argument type?

How can we constrain the return type of getStreamFor$(item: Item) based on the parameter type Item? The desired outcome is: When calling getStream$(Item.Car), the type of stream$ should be Observable<CarModel> When calling getStream$(Item.Animal), ...

Is there a way to convert a Java object into a JSON string while ensuring that all special characters are

Is there a method to transform a Java object into a string with the following criteria? It is important that all field names are properly escaped, and the records are separated by "\n". { "content":"{\"field1\":123, \"field2\":1, ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

Analyzing data from Facebook API response (JSON) to extract valuable information

As a Java Developer, I have struggled to find adequate resources for developing Facebook apps using Java. Currently, I am working on a Java-based Facebook app that involves reading a user's inbox. I have managed to create a Login flow and obtain a l ...

Can you please guide me on retrieving information from an API using HTML, CSS, and JavaScript?

My task is to develop a web application using HTML, CSS, and JS with the following functionality: Retrieve a list of users from this API: https://jsonplaceholder.typicode.com/users. Upon clicking on a user, show a list of albums associated with that user ...

Ways to determine the total amount of existing files in a directory

For the purpose of file management and moving files to another folder, I am attempting to determine the count of files that already exist in a specified folder. foreach($checkboxfiles as $checkboxfile) { $src_file = $checkboxfile; $fileName = bas ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

What is causing the warnings for a functional TypeScript multidimensional array?

I have an array of individuals stored in a nested associative array structure. Each individual is assigned to a specific location, and each location is associated with a particular timezone. Here is how I have defined my variables: interface AssociativeArr ...

An error occurs when trying to cast a JSONArray into a java.util.ArrayList

I am currently working on an Adapter class that includes a Filter, and I encountered an error in the publishResults method. The list loads fine, and filtering works when typing into the filter. However, the app crashes with an error when deleting character ...

Saving CSV files in Couchbase using JSON formatting

Currently, I am working with strings that will be concatenated gradually to a document in couchbase using clojure. The code is quite simple. ;create document when new (cbc/add client key value) ;append when document exists (c/async-prepend client key (st ...

Creating customized object mappings in Typescript

In my current Angular project, I am working on mapping the response from the following code snippet: return this.http.get(this.url) .toPromise() .then(response => response as IValueSetDictionary[]) .catch(this.handleError); The respon ...

Transforming a JSON string into a Hashie mash object

My web service returns a JSON in this format: [ { "key": "linux.ubuntu.ip", "value": "10.10.10.10" }, { "key": "linux.ubuntu.hostname", "value": "stageubuntu" } ] In my Ruby code that interacts with this se ...

In TypeScript, the argument 'xxx' cannot be passed to a parameter expecting a 'string' type

When I try to create a new Error object with the message {code: 404, msg: 'user is not existed'} in TypeScript, I receive the following error message: [ts] Argument of type '{ code: number; msg: string; }' is not assignable to paramete ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

The 'MutableRefObject<null>' type is lacking the following properties that are present in the 'Element' type

I'm eager to implement intersection observer in my React Typescript project. (https://www.npmjs.com/package/react-intersection-observer) However, I encountered an issue with setting the root: const root = useRef(null); const { ref, inView, entry } ...

Having trouble retrieving object properties within an Angular HTML template

There are two objects in my code that manage errors for a form: formErrors = { 'firstname': '', 'lastname': '', 'telnum': '', 'email': '' } ValidationMessa ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...