Tips for inserting an object into an array

Here's the data I received:

{
0:{modifierId: 4, modifierName: 'Garlic',  modifierPrice: 60 }
1:{modifierId: 1, modifierName: 'Tartar ',  modifierPrice: 60}
2:{modifierId: 3, modifierName: 'Herb ',  modifierPrice: 60}
itemId:387
itemName:"BUFFALO WINGS"
itemPrice:500
itemQuantity:0
}

I have a project in angular focused on point of sale. The idea is that when a user clicks on an itemName button, it should show its modifiers in a dialog box. All this information is fetched from a restful API. When a modifier is clicked, its object is passed into the item's object. However, when trying to display the items in the cart using ngFor*, an error occurs. Angular does not support passing objects in ngFor*, as it only works with arrays.

The desired output is:

[
0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60}
1:{modifierId: 1, modifierName: 'Tartar ',  modifierPrice: 60}
2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60}
itemId:387
itemName:"BUFFALO WINGS"
itemPrice:500
itemQuantity:0
*length:3*
]

Now, the goal is to pass the modifier's object into an array. How can I achieve this?

Answer №1

To ensure that your object is only casted as an array within the template, you can utilize the Angular keyvalue pipe:

<div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
</div>

Alternatively, in your component, you have the option to convert your object into an array using the following method:

let arr = Object.keys(obj).map((k) => obj[k])

Answer №2

Perhaps you are in search of an object similar to this:

{
    itemId:387
    itemName:"BUFFALO WINGS"
    itemPrice:500
    itemQuantity:0,
    modifiers:[
       {modifierId: 4, modifierName: 'Garlic', modifierPrice: 60},
       {modifierId: 1, modifierName: 'Tartar ',  modifierPrice: 60},
       {modifierId: 3, modifierName: 'Herb ', modifierPrice: 60}
    ]
}

(the "length" can be found at newObject.modifier.length)

    newObject={
      itemId:original.itemId,
      itemName:original.itemName,
      itemPrice:original.itemPrice,
      itemQuantity:original.itemQuantity,
      modifiers:Object.keys(original)
            .filter((key:string)=>key.indexOf('item')<0)
            .map((key:string)=>original[key])
 }

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

Service injection in Angular 4 module not functioning properly even though it was declared at the module level

Introducing my unique service named VenueAdminInceptionService import {Subject} from 'rxjs/Subject'; import {Observable} from "rxjs/Observable"; import {VenueAdminInceptionModel} from '../../models/venueadmininceptionmodel/venueadmin.incept ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

Experiencing "localhost redirect loop due to NextJS Middleware" error

After successfully integrating email/password authentication to my locally hosted NextJS app using NextAuth, I encountered an issue with the middleware I created to secure routes. Every time I tried to sign out, I received an error stating "localhost redir ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

At what point does a vulnerability in a React or Angular library become a serious threat?

As a cybersecurity student, I have noticed numerous CVEs related to libraries used in React and Angular. One example is: │ Critical │ Prototype Pollution in minimist │ ├────────────── ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

Angular applications hosted on .Net Core should include a robots.txt file to provide instructions to web

I am currently running a web application on a Windows server, built with Angular 5 for server side rendering and hosted within .Net Core. I recently uploaded a robots.txt file to the root directory of the server, but when attempting to access it via , the ...

When the input field is cleared, JavaScript will not be able to recognize its contents

Having an issue with my function that fetches results, <script language="javascript"> function fetchResult(value){ url="ajax_fetch.php?st=usr&q="+value; ajax(url); } fetchResult(" "); </script&g ...

Using Angular, you can effortlessly inject elements into the editable div from any location on the page

Currently, I am working on developing an HTML interface that allows users to input text and send it as a notification to our mobile application. However, I am encountering challenges with the text and dynamically inserted elements using Angular 5; The te ...

What is the best way to include attributes in an HTML element?

I've been researching how to dynamically add attributes to an HTML tag using jQuery. Consider the following initial HTML code: <input type="text" name="j_username" id="j_username" autocorrect="off" autocapitalize="off" style="background-image: lin ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

How does the function window.open determine whether to open a new tab or switch to an existing tab based on specific criteria?

As I navigate through new tabs and existing tabs, I am curious about the criteria that determines whether a new tab is opened or if the browser simply reopens an existing tab with the same name. Could someone shed light on the specific parameters being co ...

The set method of useState is not causing the specific component to render

My concern arises when trying to update the TaskDetail component located at Right Side. Despite changing the value of the card within the handleCardClick callback, the specific component does not reflect this change. In the provided gif, it can be observed ...

What are some strategies for improving search efficiency in arrays containing over 50,000 elements?

I am working with a large array of strings containing about 50,000 elements. export const companies = [ "000014", "000016", "000017", "000019", "000020", "000021", "000023" ...

How can I empty the value of a UI widget (such as an input field, select menu, or date picker) in Webix UI?

Is there a way in Webix UI to clear widget values individually, rather than collectively based on form id? I'm looking for a method using a mixin like $$(<form-id>).clear(). I need control of individual elements, so is there a proper way to res ...

Exploring AngularJS for real-time updates from a persistent database

Hello, I'm new to Angular and currently working on an app that requires frequent polling of a URL every second. The retrieved data needs to be stored persistently for access across multiple views and controllers. To handle this, I've placed the ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...