user
user

Reputation: 4840

Typescript - push splitted string to array

I write an application using angular 2.

I have an input and I want to enter list of string and later split them by comma.

Input: Item1, Item2, Item3

Entered string I have to split by comma.

addItems(toSplit: string) {
   splitted: string[] = toSplit.split(",");
}

And I have an object:

export class Foo {
   items: string[];
}

How can I push all splitted string to foo.items?

Upvotes: 1

Views: 2625

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48387

You can create a constructor for your typescript class.

export class Foo {
   constructor(private items: string[]){}
}

Now you can create a class object which has your splitted array.

var foo = new Foo(splitted);

Upvotes: 1

Erniukas Berniukas
Erniukas Berniukas

Reputation: 11

Try this one:)

class Split {
    splitted: string[];
    addItems(toSplit: string) {
        this.splitted = toSplit.split(",");
    }
}


export class Foo {
    items: string[];
}

var demo = new Foo();
var test = new Split();
test.addItems("Item1,Item2,Item3");

demo.items = test.splitted;

console.log(demo.items);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074595

And I have an object

That's not an object, it's a class. (Okay, granted, it's also an object.) To access items, first you need an instance to access it on:

const instanceOfFoo: Foo = new Foo();

Then, once you have that instance and you have the array from split, you can either:

  1. Replace the array on your Foo instance:

    instanceOfFoo.items = splitted;
    

    or

  2. Add those to your items (e.g., if you may do this more than once with the same Foo):

    instanceOfFoo.items.push(...splitted);
    

    That ... is spread notation, which should be supported in TypeScript via transpilation. If you want to be old-fashioned instead:

    instanceOfFoo.items.push.apply(instanceOfFoo.items, splitted);
    

If you already have the split string before you create Foo, you could provide it as an argument to the constructor and then do one of these within the constructor, whichever better suits your need:

// Using the array provided directly
export class Foo {
    constructor(public items: string[] = []) {
    }
}

or

// Copying the given array
export class Foo {
    public items: string[] = [];
    constructor(items: string[]) {
        this.items.push(...items);
    }
}

Then using either of those:

const instanceOfFoo: Foo = new Foo(splitted);

Side note: You're missing a let or const in your method (I assume it's a method, given the lack of function in front of it):

addItems(toSplit: string) {
   const splitted: string[] = toSplit.split(",");
// ^---- here, should be const or let depending on whether you want
// to be able to change it
}

Upvotes: 2

Related Questions