31

I have an array named Dish and have a form. After the form is submitted, data pushes to dish. I have tried to use the push method to add that into an array, but it throws an error. How I can do that with typescript?

Class object:

export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   comments: Comment[];
}

I have created an object named commentData from class comment to receive all data from form after submit. I also created an object named dish from class Dish. How to push an object commentData to object dish.comments?

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}

My git : https://github.com/zymethyang/Ionic_HKUST

2
  • 1
    Please add a code about your objects. Commented Sep 16, 2017 at 2:25
  • I have edited my post. Please check on top. Thank you. Commented Sep 16, 2017 at 2:52

5 Answers 5

33
let myArray = [];
let commentData = {} as Dish;
commentData.id = 3;
commentData.name = 'something';
myArray.push(commentData);

It will work...

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, but i have a new comments and want to pushed to the existing dish.comments.
10

#Answer

Answer on how to push Comment (object) into Dish.comments (array) in TypeScript.


export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   // comments: Comment[]; // remove this
   comments: Array<Comment>; // <--- change to this. everytime you want to add array use Array<YourInterface>
}

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}

dish.comments.push(commentData);

View live code on TypeScript Playground and click RUN.

As you see in the above code. You need to change Comment[] into Array<Comment>.

#Explanation

Generic Type Variables

Array<T> or Array<Type>

You may already be familiar with this style of type from other languages such as Java and C#.

We have Generic Type Variables in typescript too.

Another way to use Generic Type Variables:

Here's an example of an array with multiple types:


let x: Array<string | number>
x = ["hello", "world", 2]

This second version is common if your array consists of different types of objects. For example:

interface Boat {
  name: string
}

interface SpaceShip {
  code: number
}

interface Wagon {
  active: boolean
}

let inventory: Array<Boat | SpaceShip | Wagon> = [];

let boatData: Boat = {
  name: "Boat 1"
}

let spaceShipData: SpaceShip = {
  code: 1234
}

let wagonData: Wagon = {
  active: true
}

inventory.push(boatData);
inventory.push(spaceShipData);
inventory.push(wagonData);

console.log(inventory);

View live code on TypeScript Playground and click RUN.

You can learn more about Generic Type Variables here and here

3 Comments

@Nima What's wrong with my answer? I corrected his code (answering how to push an object to array in TypeScript) and explained about how to use Generic Type Variables to learn more about this kind of staff.
@Nima You can read my updated answer and I added a link to TypeScript Playground with edited code to show you that my answer works.
1. Actually there is no different between Array<...> and Comment[] from OP question! 2. dish.comment.push{/*all fields of Comment with value should work*/}); 3. my playgound link is too long that I cannot put it in here ....
6

If you simply need to add the new commentData after each form submission (if I understood you correctly), all you need is this every time you want the new comments to be pushed to the existing dish.comments,

this.dish.comments = this.dish.comments.push(this.commentData); // assuming these are class properties, hence the 'this' usage

Does that work for you?

EDIT

Modify the first line

this.commentData = this.comment.value;

in dismiss() method to this,

this.commentData.author = this.comment.get('author').value;
this.commentData.rating = this.comment.get('rating').value;
this.commentData.comment = this.comment.get('comment').value;

7 Comments

Yes, that's what i want but it's not working. [ts] Type 'number' is not assignable to type 'Comment[]'. (property) Dish.comments: Comment[]
Interesting, where does the number come from? Can you show an example of your commentData object?
Sample of commentData object. { "rating": 5, "comment": "Imagine all the eatables, living in conFusion!", "author": "John Lemon", "date": "2012-10-16T17:57:28.556094Z" },
If either of your models (interfaces) don't exactly match to their respective objects, then this error can happen. May be you have to check your object structure and 'optionalize' certain properties in the interface declaration using the ? symbol like, for ex: rating?: number;
This 's my git github.com/zymethyang/Ionic_HKUST. Could you help me fix it. This is dismiss() method on comment.ts. Thank you.
|
4

If you need to add multiple objects to an array inside a loop:

let thingsArray = [];

someArray.forEach(doc => {
    let thingsObj = {} as Thingy;

    thingsObj.weekDue = doc.name;
    thingsObj.title = doc.age;
    thingsArray.push(thingsObj);

}).then(() => {
    console.log(thingsArray);
}

Comments

1

let arraylist= [];
let obj1 = {} as Class;
obj1.id = 1;
obj1.name = 'text';
let obj2 = {} as Class;
obj2.id = 1;
obj2.name = 'text';
arraylist =[obj1,obj2 ];

This work for me but I tried it with Classes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.