javascriptangulartypescriptecmascript-6

how to generate the next item id when creating a new post?


How to generate the next ID in the post, if in the add method, I add only "title" and "url"?

Method:

    addPost(title:string, url:string):void {
    const post = {
        title:title,
        url: url
    };
    this.collection.push(post);
}

Template where i show post:

        <img [src]="pic.url" alt="test" class="img-responsive">
<p class="lead"><span>{{pic.id}}:</span>{{pic.title}}</p>
<div class="del">
    <button class="btn btn-outline-danger (click)="removePost(pic.id)">Delete</button></div>

Interface of input data:

export interface Picture {
  id?: number,
  title: string,
  url: string
}

Last post in my array:

{
  id: 10,
  title: "beatae et provident et ut vel",
  url: "https://placekitten.com/200/200",
}

Solution

  • If you are using lodash use lodash last method:

    addPost(title:string, url:string):void {
      const post = {
        title:title,
        url: url,
        id: _.last(this.collection).id + 1
    };
    this.collection.push(post);
    

    Else if pure JavaScript:

    addPost(title:string, url:string):void {
      const post = {
        title:title,
        url: url,
        id: this.collection[this.collection.length -1].id + 1
    };
    this.collection.push(post);
    

    This assumes that the next ID will be the ID plus one of the last object in your collection.

    You would probably also need to introduce some defensive code to set the ID as 1 if the collection is currently empty.

    You could also just use a GUID or UUID generator, see the very popular npm uuid module.