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

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

MUI Error: Incorrect prop provided to menu item

I am encountering an issue with a React component that generates a list of elements, each containing a button to open a menu. The problem is that the props being passed to each menu are incorrect; they always reflect the props of the last element in the ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

tslint is flagging an error related to cyclomatic complexity

Within my Angular 8 project, the following dependencies are utilized: "codelyzer": "^5.1.0", "ts-node": "~8.3.0", "tslint": "~5.19.0", Upon executing: ng lint myapp --fix=true An error is raised stating: ERROR: ...html:428:106 - The cyclomatic complex ...

Vercel and Firebase Realtime Database causing snapshot.val() to return null during build deployment

Creating a blog application using Next.js, Firebase Realtime Database, and Vercel for hosting has been seamless on my local machine. Even after running npm run build, everything functions perfectly. However, when deployed to Netlify in production, the snap ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example: <div ng-repeat="outeritem in outerobject"> <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div> <d ...

Is there a way to retrieve a compilation of custom directives that have been implemented on the Vue 3 component?

Is there a way to retrieve the list of custom directives applied to a component? When using the getCurrentInstance method, the directives property is null for the current component. I was expecting to see 'highlight' listed. How can I access the ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

Using JavaScript for Array manipulations

Here's a string that I want to convert into an array: "["Arr1","Arr2"]" To achieve the desired format, I need to remove the first and last characters so it looks like this: ["Arr1","Arr2"]. I've attempted using the slice function in this wa ...

Can you explain the process of utilizing a JavaScript function that has been fetched via Ajax

When the AJAX function is loaded on the page, I am attempting to execute another function. The code snippet for the AJAX call: $.ajax({ type: "POST", url: "loginpersonal.asp", data: "id=<%=request("id")%>", beforeSend: function() { $("#personal ...

Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see th ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

Personalized AngularJS required text

After utilizing the built-in AngularJS directive required and encountering a validation error, I receive a small popup near the field displaying "Please fill out this field". My issue lies in needing the text to be displayed in another language. How should ...

Transferring information between two distinct components

I am facing an issue where I have a list of stores shown in an unordered list, and when this list is initialized the ngOnInit() function retrieves data for all the stores. However, I want to be able to send the store data from each list element to the stor ...

When using Playwright, there may arise a requirement to reuse a specific UUID that has been defined in one test within another

I have two separate tests running in parallel, each creating a different company in my test environment. However, I need to access the uuid of both companies in later tests. I am looking for a way to store these uuids so they can be used across all subseq ...

I am unable to eliminate the parentheses from the URL

I am in need of creating a function that can extract the content inside "()"" from a URL: Despite my efforts, the function I attempted to use did not provide the desired result. Instead of removing the "()" as intended, it encoded the URL into this format ...