Generate fresh instances of object(s) using JSON information

After receiving JSON data from a service call, I am presented with the following structure:

myArray: any = [
{item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"},
{item: 'Skittles', areaCode: 444, Company: "Jim's Candy"},
{item: 'Snickers', areaCode: 321, Company: "Bob's Candy"},
{item: 'M&Ms', areaCode: 444, Company: "Jim's Candy"},
{item: 'Gummy Bears', areaCode: 123, Company: "Sally's Candy"}];

My goal is to dynamically split this data into multiple arrays of objects based on their respective areaCodes.

Alternatively, creating a new object dynamically for each unique areaCode is another option.

this.myArray= this.data.map(item => item.areaCode)
.filter((value, index, self) => self.indexOf(value) === index);

I am considering using the map function to filter the data by areaCode and then possibly organizing it into new objects, but I'm struggling with visualizing the process. Any guidance or advice on how to approach this would be greatly appreciated.

Answer №1

Here is the expected output:

{
"123":[{"item":"Gummy Bears","areaCode":123,"Company":"Sally's Candy"}],
  "321":[{"item":"Jelly Beans","areaCode":321,"Company":"Bob's Candy"}, 
         {"item":"Snickers","areaCode":321,"Company":"Bob's Candy"}],
  "444":[{"item":"Skittles","areaCode":444,"Company":"Jim's Candy"}, 
         {"item":"M&Ms","areaCode":444,"Company":"Jim's Candy"}]
}

To achieve this output, you can use the following reduction method:

const output = myArray.reduce((res,v) => {
    if(!res[v.areaCode]) {
        res[v.areaCode] = [v] 
    } else {
    res[v.areaCode].push(v)
    }
return res
},{} )

Answer №2

To transform your array into an object, you can utilize the .reduce method. Subsequently, you can employ Object.values() to extract a collection of distinct objects from the transformed object in the following manner:

const arr = [
{item: 'Jelly Beans', areaCode: 321, Company: "Bob's Candy"},
{item: 'Skittles', areaCode: 444, Company: "Jim's Candy"},
{item: 'Snickers', areaCode: 321, Company: "Bob's Candy"},
{item: 'M&Ms', areaCode: 444, Company: "Jim's Candy"},
{item: 'Gummy Bears', areaCode: 123, Company: "Sally's Candy"}];

const res = Object.values(arr.reduce((acc, {item, areaCode, Company}) => {
  if(areaCode in acc) {
    acc[areaCode].item.push(item);
  } else {
    acc[areaCode] = {item: [item], areaCode, Company};
  };
  
  return acc;
}, {}));

console.log(res);

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

What is the method for deserializing in Scala using lift-json without requiring knowledge of the concrete type

Using lift-json 2.0 along with Scala classes and a sealed trait, the scenario involves: sealed trait Location case class Coordinate(latitude: Double, longitude: Double) extends Location case class Address(...) extends Location The ...

What causes BehaviorSubjects in Angular RXJS to emit multiple values?

click here to see the image descriptionUsing BehaviorSubject for sharing data between components in my app has led to a performance problem caused by multiple emissions of the same value. For example, when I make an HTTP call to fetch a team object from th ...

Launching ES Lint to handle SetStateAction within a TypeScript interface

Here is the component I have: import React, { SetStateAction } from 'react'; interface ColorObject { name: string, slug: string, hex: string, } interface Props { color: ColorObject onClick: React.Dispatch<SetStateAction<ColorObj ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Using Mongo Node Angular all in one server

Is it advisable to host Angular, Node-express, and Mongo on the same server, such as localhost:3000 or somehosting.com/server-address? Would this be considered a best practice? I have seen Angular and Node running together on the same server, but what abo ...

Utilizing the moment function within an Angular application

I've successfully added the library moment.js by running: npm i moment I've included it in scripts and attempted to import it in module.ts. However, when I try to use moment in component.ts, I'm getting an error that says: 'canno ...

Define the output type of an arrow function within an interface signature

How can I inform typescript that I will be utilizing an interface containing a function called "foo" which always returns a string. The implementation of the function will be specified by the object implementing the interface. For example: export interfac ...

Trying to install the Angular app post CLI installation is proving to be a problem for me

Below is an excerpt from the log showing where the error is logged. It seems that the error changes with each installation attempt. 2516 silly saveTree `-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="add7c2c3c883c7deed9d8 ...

Unable to display custom component on app.component.html

After creating a unique custom component named core.component, I proceeded to import it into a module with the same name. core.component.html <div class="container-fluid text-left"> <div class="row rows-cols-2 top-bar"> ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

What is the best way to achieve accurate type inference when working with a union type that includes optional properties as the React prop type?

How can I ensure proper type inference for v when a is optional in a union type? import React from 'react'; type A = { a?: false; s: (v: number) => void }; type B = { a: true; s: (v: string) => void }; type Props = A | B; const Comp: React ...

Transferring PHP data into JSON format

As a beginner in JSON syntax, I am seeking guidance on how to transfer results retrieved from a database using PHP into a JSON code. Here is the code snippet: <?php $id_num = urldecode(intval($_REQUEST['id_cod'])); $rs = $list ...

What could be the reason for my FormData object being consistently devoid of content?

I am attempting to populate formData with data using the following method: params = {'code': 'h1'} const formData: FormData = new FormData(); formData.append('parameters', JSON.stringify(params)); Once I attempt to access th ...

Child components in Angular 2+ successfully animate when entering, but struggle to animate when leaving

One of my sub-components looks like this: @Component({ selector: 'is-time-controlled', templateUrl: './is-time-controlled.html', styleUrls: ['./is-time-controlled.less'], animations: [ trigger( 'myAnimation&a ...

Exploring arrays in C++ to identify repeated numbers

Currently studying C++ and encountering an issue in my code that I'm having trouble pinpointing. It seems like the problem lies in the stat array incrementation, which is supposed to count how many numbers are repeated in the T array. How can I rectif ...

Mockery Madness - Exploring the art of mocking a function post-testing a route

Before mocking the process function within the GatewayImpl class to return the 'mockData' payload, I need to ensure that all routes are tested. import payload from './payloads/payloadRequire'; // payload for request import {Gate ...

Ignore error alerts during numpy array calculations

Is it possible to use "try-except" to handle errors in order to insert np.nan into the result array? For example: import numpy as np a = np.array([1,1]) b = np.array([1,0]) c = a/b When a "division by zero error" occurs, I would like to ignore it and ha ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

What is the best way to extract the JSON viewport data from the Google Places API

After sending a request from my iOS app to the Google Places API, the response I received includes the following data: { "html_attributions" : [], "result" : { "address_components" : [ { "long_name" : "Rome", "short_name" : "Rome", ...

When all observables have finished, CombineLatest will only execute one time

I've encountered a problem that requires me to use a combination of 3 route observables to open a modal. Here is the logic in my code: combineLatest([obs1, obs2, obs3]) .subscribe(([s1, s2, s3]: any) => { openModal(); }); The issu ...