Angular 2: Converting JSON data into an array

I am working with JSON data that contains vendor fields and I need to extract unique vendors into an array. Can someone provide guidance on how to achieve this in an Angular2 component?

Here is the sample data:

[{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Klaussner"},
{"category": "Living Room", "vendor": "Flexsteel"},
{"category": "Living Room", "vendor": "Craftmaster"},
{"category": "Living Room", "vendor": "Craftmaster"}]

I would like the resulting array to display only the unique vendors:

[{"vendor": "Flexsteel"},
{"vendor": "Klaussner"},
{"vendor": "Craftmaster"}]

Answer №1

Give this a shot:

const info = [...data here...];

const suppliers = info.map(d => {
  return { supplier: d.supplier };
});

Answer №2

An efficient way to achieve this is by using the Array.map method:

let products = [
        {"category": "Bedroom", "vendor": "Ashley Furniture"},
        {"category": "Bedroom", "vendor": "IKEA"},
        {"category": "Bedroom", "vendor": "Rooms To Go"},
        {"category": "Bedroom", "vendor": "Bob's Discount Furniture"}
      ];
let processedProducts = products.map(product => ({ vendor: product.vendor }));

Answer №3

To start, you will first need to acquire the vendors. Here is an example of how you can do this:

let data = [{"category": "Living Room", "vendor": "Flexsteel"},
            {"category": "Living Room", "vendor": "Klaussner"},
            {"category": "Living Room", "vendor": "Flexsteel"},
            {"category": "Living Room", "vendor": "Craftmaster"}];

// Extract all the vendors 
let vendors = data.map(dat => ({ vendor: dat.vendor }));

Next, you must filter the vendors list to obtain only unique vendors by utilizing the following code snippet:

// Unique Vendors 
let uniqueVendors= Array.from(new Set(vendors.map((x) => JSON.stringify(x))))
                                             .map((y) => JSON.parse(y.toString()));

Here is the complete code snippet for reference:

let data = [{"category": "Living Room", "vendor": "Flexsteel"},
            {"category": "Living Room", "vendor": "Klaussner"},
            {"category": "Living Room", "vendor": "Flexsteel"},
            {"category": "Living Room", "vendor": "Craftmaster"}];

// Get all the vendors 
let vendors = data.map(dat => ({ vendor: dat.vendor }));

let uniqueVendors= Array.from(new Set(vendors.map((x) => JSON.stringify(x))))
                                             .map((y) => JSON.parse(y.toString()));
                                             
console.log(uniqueVendors)

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

"Obtaining the document object within an Angular component: A step-by

Is there a way to access the document object in Angular? I've attempted using ElementRef but it doesn't seem to be working. let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor'); Does anyone have any suggestions ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

Managing state in a large Angular application can be quite challenging

Recently, a unique situation arose within our application that sparked my curiosity. After an extensive search for a solution, I was unable to find a definitive answer. Our application boasts over 600 modules, each with its own set of states and data. I ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

Using ES6 import with the 'request' npm module: A Step-by-Step Guide

When updating TypeScript code to ES6 (which runs in the browser and Node server, with a goal of tree-shaking the browser bundle), I am attempting to replace all instances of require with import. However, I encountered an issue... import * as request from ...

Component with a dynamic CSS file implementation

I am looking to empower users of my app with the option to select a theme. To achieve this, I have created multiple SCSS stylesheets that offer variations in design elements. However, I am faced with the challenge of loading the appropriate stylesheet base ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

When using the .concat method on an array, props may display as unidentified

When I log the items array in my props, it contains items. However, when I try to add to the array using .concat, I encounter an error stating Cannot read property 'concat' of undefined export default (props) => { const { items } = props; ...

Switching a parameter from a string to an object will cause Elasticsearch to be unable to properly index the new data structure

I have a collection of items stored in a Firebase database that I am using in conjunction with ElasticSearch for advanced queries. Recently, I had to update the structure of one of the items from a simple string, organizer: "some name", to a more complex ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

The TypeScript compilation failed for the Next.js module

Working on a project using Next.js with typescript. The dev server was running smoothly, and I could see frontend changes instantly. However, after modifying the next.config.js file and restarting the server (later reverting the changes), compilation issue ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Convert a TypeScript array of strings to a boolean array: a step-by-step guide

Upon receiving a list of objects from the front end as: item=["false","true"] I proceed to check a column within my records to identify values containing "true" or "false" using the following code: this.records.filter(x=> items.includes(x.column)) Unf ...

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

Following a docker run command, Docker undergoes an automatic shutdown process

I am currently working on an Angular 7 application and I'm looking to deploy it using Docker. I have created a Dockerfile in the root folder, but when I attempt to run Docker, it seems to terminate unexpectedly. Below is the content of my Dockerfile: ...

What are the methods to determine the cause of ESLint's slow performance?

Looking to analyze the performance of ESLint in my application. So far, I have only come across one profiling tool provided by ESLint which is the TIMING=1 environment variable. Combining this with DEBUG=eslint:cli-engine allows me to see timing results pe ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

typescript, generate a new type by merging option values

In typescript I am faced with a challenge. I have a type called A: interface A { a1: string; a2: int; } As well as another type called B: interface B { b1: number } Now, my goal is to create a new type: interface AB { a1?: string; a2? ...