Loop repeating works in one case, but does not work in another (JS)

Asked

Viewed 38 times

0

I am not able to understand why the loop below works to assign a new value to the index, but does not work to change the property of an object. What I did wrong, you guys?

var p = ["teste1", "teste2", "teste3", "teste4"];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]); // AQUI O LAÇO FUNCIONA.
        var people = [
          {
            name: p[key],
            url: "http://example.com/johnsmith"
          }
        ];        
        console.log(people[key]); // AQUI O LAÇO NÃO FUNCIONA. =\
    }
}

1 answer

2


When you call people[key], tries to access a position specified by key. However, you are overriding the content of your vector people with each iteration on p, making this vector always have only 1 item.

I suppose you want to go through p and, for each item, insert an object into people, with the same name as p[key] and the url defined. Therefore, the vector must be initialized before the loop for and add the object using push.

var p = ["teste1", "teste2", "teste3", "teste4"];
var people = [];

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(`${key} -> ${p[key]}`);

    people.push({
      name: p[key],
      url: "http://example.com/johnsmith"
    })

    console.log(people[key]);
  }
}

  • Exactly as you guessed, Lucas! Thank you very much for the tip, my dear!

  • Not to mention I didn’t know the push method()! :)

  • Glad I could help! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.