0

I'm trying to extract all elements from an array but instead i'm getting the last element of it
This is my code:

// this.data contains data from a http.get
// I tried using user: [] and user: any = [];  
user: Array; // 
pass: Array;
for (const x of this.data) {
                this.user = x.username;
                this.pass = x.password;
           } // console.log(this.user); Output = lastelementfromthearray
5
  • Same question here: stackoverflow.com/questions/31277004/… Commented Apr 7, 2018 at 21:15
  • What does the mc object have to do with the content of the array? Anyway, apart from that, your problem is that you are overriding this.user at every iteration, which means that you'll only get the final one at the end of the loop. Commented Apr 7, 2018 at 21:33
  • @Lior Yeah but i don't want to access to certain one, i want to acces to all of them. Commented Apr 7, 2018 at 22:18
  • @bugs My bad, i updated it. So in that case what do you recommend me to do? Commented Apr 7, 2018 at 22:19
  • 1
    So, you already have an array (data), containing everything you need. There is nothing to extract. data is what you want: the array of username/passwords. Commented Apr 7, 2018 at 22:22

2 Answers 2

1

If you need to have an array of some fields from objects that are contained in another array, it's:

this.user = this.data.map(({ username }) => username);
this.pass = this.data.map(({ password }) => password);

If the array is big enough or the place is performance-critical, this can be done in a single loop, preferably for/while:

this.user = [];
this.pass = [];

for (let i = 0; i < this.data.length; i++) {
  this.user.push(this.data[i].username);
  this.pass.push(this.data[i].password);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Right now, you are overriding this.user at each iteration. Since this.user is an array, what you want to do is instead pushing x.username to the array. the same of course applies to the other array.

    user = [];
    pass = [];
    for (const x of this.data) {
      this.user.push(x.username);
      this.pass.push(x.password);
    }

2 Comments

You also have to initialise the arrays, I've modified the answer
It worked but not as i expected because it saves all(username and password) elements in this.user instead of dividing this.user(x.username) and this.pass(x.password)

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.