Limna
Limna

Reputation: 403

VueJs: push value with key in array

I have an array EventsList. But it doesn't have id column. So I need to push value with key into List1 and List2 from EventsList. Can we do with the below code.

this.GetEventsList().then(response=>{
        if(response.data){
            _self.EventsList=response.data;
            _self.EventsList.forEach (function(events){
                if(events.category == "a")
                    _self.List1.push(events);
                else
                    _self.List2.push(events);
            });
        }
    });

Upvotes: 0

Views: 2240

Answers (1)

Dylan
Dylan

Reputation: 1118

You could just have a count be the id and push it as a object into the list. You could also use the length of the current list as the id if you are going to continuously add items to the same list.

this.GetEventsList().then(response=>{
    if(response.data){
        _self.EventsList=response.data;
        var count = 0;
        _self.EventsList.forEach (function(events){
            if(events.category == "a")
                _self.List1.push({id:count,events:events});
            else
                _self.List1.push({id:count,events:events});

            count++;
        });
    }
});

Upvotes: 2

Related Questions