``There are problems with parsing JSON data due to the error message indicating the presence of unexpected

I am encountering an issue with displaying values from objects stored as string[] in appwriteDB. When trying to use *ngFor to iterate through the data, I faced difficulties. Despite attempting to convert the orderItems using JSON.parse(), the process failed due to unexpected white space detection.

    [
      {
        "orderStatus": "New",
        "orderPayment": "Paid",
        "orderItems": [
          "{\"productName\":\"Nokia Windows mobile\",\"productPrice\":299,\"productDetails\":\"Nokia windows 10 mobile\",\"productAvailable\":true,\"qty\":1,\"$id\":\"65f21c5cdd3449f30f68\",\"$createdAt\":\"2024-03-13T21:36:28.906+00:00\",\"$updatedAt\":\"2024-03-13T21:36:28.906+00:00\",\"$permissions\":[],\"$databaseId\":\"smartCartDB\",\"$collectionId\":\"Products\"}"
        ],
        "$id": "65f6fcc4e65c46fc6e97",
        "$createdAt": "2024-03-17T14:23:00.944+00:00",
        "$updatedAt": "2024-03-17T14:23:00.944+00:00",
        "$permissions": [],
        "products": [],
        "$databaseId": "smartCartDB",
        "$collectionId": "Orders"
      }, ...

Efforts to resolve this through JSON.parse have proven unsuccessful. What would be the most effective strategy for converting the specific orderItems object?

method:1

res.documents.map((el:any) => {return JSON.parse(el.orderItems)} ));

method:2

res.documents.map((el:any) => {
    return el.orderItems.map((el2:any) => {return JSON.parse(el2)})
})

I seek guidance on the optimal approach to address my current predicament.

Answer №1

The issue stems from attempting to JSON.parse(el.orderItems)}, where orderItems is a collection of strings. Instead, it's necessary to iterate through the orderItems and stringify each individual string. Here's how you can accomplish this:

const result = data.map((order) => {
    return order.orderItems.map((item) => {
        return JSON.parse(item)
    })
})

Answer №2

To correctly parse the array of objects in orderItems, you can simply use JSON.parse(data). This is how the code should look:

    const parsedData = data.map(item => {
      return {
        ...item,
        orderItems: [item.orderItems.map(order => JSON.parse(order))]
      }
    })

If you want to test this code snippet, you can do so on a sandbox environment by following this link: https://jsfiddle.net/9kr2LJt0/

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

Alternating the main access point from a separate module

I'm finding it difficult to understand why this should be so simple, but I just can't seem to solve this issue. Within my application, I have various root routes like login, events, and more. To manage the main menu functionality, I created a mo ...

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

I am unable to process the information and transform it into a straightforward list

When using ngrx, I am able to retrieve two distinct data sets from storage. private getCatalog() { this.catalogStore.select(CatalogStoreSelectors.selectAllCatalogsLoadSuccess) .pipe( takeWhile(() => this.alive), take(1), ...

Design a unique login portal separate from all other website pages

I'm a beginner with Angular and I'm currently working on creating a login page. My issue is that I want the login page to be the only component displayed initially, and once the response is 200, I want to redirect to another component. Here&apos ...

Encountering a roadblock while trying to install a package using NPM, as the installation process becomes halted at version [email 

Having trouble installing @angular/cli via npm. It seems to get stuck every time while trying to download the package chokidar. https://example.com/image.png Here is some diagnostic information: npm version 5.0.0 node version 8.0.0 OS: Windows 7 ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Issue with handsontable numbro library occurs exclusively in the production build

Encountering an error while attempting to add a row to my handsontable instance: core.js.pre-build-optimizer.js:15724 ERROR RangeError: toFixed() digits argument must be between 0 and 100 at Number.toFixed () at h (numbro.min.js.pre-build-op ...

What is the best way to determine which component/service is triggering a method within an Angular 2 or 4 service?

Is there a way to determine which component or service is triggering the method of a specific service, without the need to pass additional parameters? This information must be identified directly within the service. If you have any insights on how this c ...

Managing nested request bodies in NestJS for POST operations

A client submits the following data to a REST endpoint: { "name":"Harry potter", "address":{ "street":"ABC Street", "pincode":"123", "geo":{ &q ...

Integrate service once the constructor has completed execution

I created a service to connect with the Spotify API. When initializing this service in the constructor, it needs to retrieve the access token by subscribing to an Observable. However, there's an issue: The service is injected into my main component ...

Tips for properly formatting a fixed table header

I'm currently facing an issue with the sticky header style in my data table. I have created a simple Angular component along with a specific directive: sticky.directive.ts @Directive({ selector: '[sticky]' }) export class StickyDirecti ...

The parameter type '{ src: string; thumb: string; }' cannot be assigned to the 'never' type in the argument

Sample Typescript Code: I am experiencing issues with my code and cannot comprehend this error message- Argument of type '{ src: string; thumb: string; }' is not assignable to parameter of type 'never' _albums = []; constructor( ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Challenges faced when integrating Angular with Bootstrap elements

I am currently in the process of developing a website using Angular 12, and although it may not be relevant, I am also incorporating SCSS into my project. One issue that I have encountered pertains to the bootstrap module, specifically with components such ...

Which would be more effective: implementing Spring Security for role-based authorization, using Angular Route Guards, or combining both approaches?

I'm currently working on a project using Spring Boot for the backend and Angular for the front end. I'm wondering if it's best practice to implement both Spring Security role-based authentication and Angular route guards, or if just using Sp ...

Can you please provide the origin of this Material 2 example document?

Click here to check out the extensive examples that delve deep into various ways of using Angular 2 Material 2 components. I'm struggling to locate the source of these examples in order to fully comprehend their implementation. Is there a specific p ...

Generate a basic collection of strings from an object

Looking at this object structure Names = [ { group: 'BII', categories: null }, { group: 'GVL', categories: [] } ]; I ...

Ways to incorporate suspense with NextJS 14 - how can I do it?

I am looking to add a suspense effect to the initial loading of my page while the assets are being fetched. These assets include images on the home screen or as children of the RootLayout component. How can I implement an initial Loading state for these ...