Remove a property from an object contained in an array

Asked

Viewed 11,673 times

12

I have a variable array:

Bola = [];

I added the properties to it:

Bola[0] = { peso:0.5, cor:"branca", marca:"nike", nota:8 };
Bola[1] = { peso:0.7, cor:"verde", marca:"adidas", nota:9  };

I would like to remove the properties "brand" and "weight". How do I do this?

  • 6

    delete Ball[0]. weight ?

  • I didn’t even know about this delete!

2 answers

15


You can use the delete to remove properties of objects within the array (which is what you have, two objects within the array bola.

// Não esqueça o var!
var bola = [];
bola[0] = { peso:0.5, cor:"branca", marca:"nike", nota:8 };
bola[1] = { peso:0.7, cor:"verde", marca:"adidas", nota:9  };

for(var i=0; i<bola.length; i++) {
    delete bola[i].marca;
    delete bola[i].peso;
}
document.body.innerHTML = JSON.stringify(bola);

Note: use lowercase to name variables, leave uppercase initials for "classes" (constructor functions).

-3

There is currently a better way to do this!

// Para arrays usa palavra no plural!
const bolas = [];
bolas[0] = { peso:0.5, cor:"branca", marca:"nike", nota:8 };
bolas[1] = { peso:0.7, cor:"verde", marca:"adidas", nota:9  };

const novasBolas = bolas.map(bola => ({
  peso: bola.peso,
  cor: bola.cor
})

In the above example, this map function is similar to the foreach, but it returns a new array.

  1. For each element I do an operation.
  2. In the operation I make an implicit return of an object.
  3. In the return object I pass only the values I want to use.
  • 1

    Hello Arthur. Nice of you to be interested in participating, but I have to say, I wouldn’t say Array.map() is better, actually it’s the other way around, it’s worse, the internal operations get more expensive. Of course in a small array you don’t notice this.

  • 1

    My -1 is because I say it’s a better way, which is a very serious mistake. I think it’s cool to show it as an alternative, but I’d have to make a mistake to make it positive. Remembering that as part of the philosophy of the site, every post can be edited to improve or correct, and every vote can be reviewed after an issue. Note, I think if I take the opinion part, really will be a great answer to complement.

Browser other questions tagged

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