Home > OS >  How to pass object into array
How to pass object into array

Time:11-24

Output what I got

{
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 am working on a point of sale project using angular The concept is when the user clicks on itemName button, it will display it's modifiers in a dialog box. All this data is coming from restful API. When I click on a modifier, it's object is passed into the item's object. In that case, when I call the items to display in cart using ngFor*, it gives an error. Because angular does not allow objects to be passed in ngFor*, it only works with arrays.

Output I expect

[
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 what I want is, to pass the modifier's object into an array. So, how can I do that

CodePudding user response:

If you want your object to be casted in array only in the template then you could use the angular keyvalue pipe:

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

Or in your component you can cast your object into an array like:

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

CodePudding user response:

I imagine you really want get an object like

{
    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" are 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])
 }
  • Related