kellzerIrl
kellzerIrl

Reputation: 101

How to increment the properties of an object in Javascript?

I'm trying to create a table that is populated from an arraylist that can vary in size, depending on user input. I need to create a new instance of "existingStrings" on each iteration of the array. At the moment only the last value ("c" for i=2) is being displayed, which is what I would expect for what I have done below. The problem that I have is how can I create a new instance of "existingString" on each iteration so that the object (this.collection) contains the attribute "existingStrings" 3 times (once for each element of the array).

this.stringList=["a","b","c"];


for (var i=0; i<this.stringList.length; i++){
        this.collection = [  
            {"existingStrings": this.stringList[i]},
        ];
        }

I would like this.collection to end up like this below:

this.collection=[{"existingStrings":"a"},
                 {"existingStrings":"b"},
                 {"existingStrings":"c"}]"

Upvotes: 1

Views: 1143

Answers (3)

kaspermoerch
kaspermoerch

Reputation: 16570

I'm not sure this is what you're looking for, but you could push the object to this.collection:

var stringList = ["a","b","c"];

stringList.forEach(function(item) {
    if(!this.collection) {
        this.collection = [];
    }

    this.collection.push({"existingStrings": item});
});

This would leave you with the output (the content of this.collection):

[{"existingStrings": "a"}, {"existingStrings": "b"}, {"existingStrings": "c"}]

Upvotes: 0

topless
topless

Reputation: 8221

You need to push, the results in the collection and not override them

var stringList=["a","b","c"];
var collection = []
for (var i=0; i<stringList.length; i++){
    collection.push({"existingStrings": stringList[i]});
}

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25892

Try this

var stringList=["a","b","c"];
this.collection = []

for (var i=0; i<this.stringList.length; i++){
        this.collection.push({"existingStrings": this.stringList[i]});
        }

Upvotes: 4

Related Questions