Does splice remove an object from the array?

Asked

Viewed 402 times

0

I have a question in Javascript.

When I splice an array, it removes what?

For example, I have an array with several objects inside, as in the example below:

lixo: [
  {"nome": "garrafa pet", "tipo": "reciclável", "cod": 12, "armazenavel": false},
  {"nome": "lata de ref.", "tipo": "não reciclável", "cod": 22, "armazenavel": true},
  {"nome": "lapis de cor", "tipo": "não reciclável", "cod": 107, "armazenavel": false},
],

If I do it here:

for(let i = 0; i <= lixo.lenght; i++){
  if(lixo[i].nome == "lata de ref."{
     let coleta = lixo.splice(i, 1)
  }
}

In this case above, after I circled the for and entered the if, the Collection variable will receive what? by chance it receives another array with the object of the ref. can inside? or Collection will only be an object of the ref can.?

If it is a collecting array that is receiving, how do I make it store only the object of the ref can.? Like this, I don’t want it to receive an array of a single object from the ref can.. In case, I want that collection receives only the object extracted from the array.

Does anyone know how to collect receiving only an object and not an array with an object inside?

1 answer

-1

In addition to removing, the .splice() will create another array with the object, in your case, the one found in if. Soon, coleta would be an array like:

coleta = 
[0]: {"nome": "lata de ref.", "tipo": "não reciclável", "cod": 22, "armazenavel": true}

See that creates an array with an index [0] with an object inside.

You can extract this object from the array by taking the index [0]:

coleta[0]

Only if you use let coleta within the if, the variable coleta will be accessible nowhere outside the if, because of the block scope of the let. Then state the let coleta outside the if to have a wider scope where you can use it:

const lixo = [
  {"nome": "garrafa pet", "tipo": "reciclável", "cod": 12, "armazenavel": false},
  {"nome": "lata de ref.", "tipo": "não reciclável", "cod": 22, "armazenavel": true},
  {"nome": "lapis de cor", "tipo": "não reciclável", "cod": 107, "armazenavel": false},
]

let coleta;

for(let i = 0; i < lixo.length; i++){
  if(lixo[i].nome == "lata de ref."){
     coleta = lixo.splice(i, 1)
  }
}

coleta = coleta[0];
console.log("coleta: ",coleta);

As well as the object found will also be removed from the original array lixo:

const lixo = [
  {"nome": "garrafa pet", "tipo": "reciclável", "cod": 12, "armazenavel": false},
  {"nome": "lata de ref.", "tipo": "não reciclável", "cod": 22, "armazenavel": true},
  {"nome": "lapis de cor", "tipo": "não reciclável", "cod": 107, "armazenavel": false},
]

let coleta;

for(let i = 0; i < lixo.length; i++){
  if(lixo[i].nome == "lata de ref."){
     coleta = lixo.splice(i, 1)
  }
}

coleta = coleta[0];
console.log("lixo: ", lixo);

Browser other questions tagged

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