How to set an equal value for an object property on all objects in a list?

Asked

Viewed 67 times

1

How to set a value for a property in all list indices without looping?

object:

var objeto = {
  nome: "",
  ativo: false
}

list:

[{"nome": "Carlos","ativo":false},{"nome": "Joao","ativo":false}]

In this example, everyone should have the active property changed to true.

The way it solves:

    for (var i in lista) {
         lista[i].ativo = true;        
    }

Is there any way to avoid that loop, make that change all at once? because in actual application the object is more complex and has many records, leaving this method slow.

  • 1

    Without making a loop should not give, maybe it is possible to optimize this loop to be faster. It doesn’t make much sense to be able to access all the items on a list without having to go through them all.

  • 1

    If you don’t make one loop, someone will be doing behind, in case there is a library that does this.

1 answer

4


Considering the entry:

let data = [
    {"nome": "Carlos","ativo": false},
    {"nome": "Joao","ativo": false}
];

In the ES6 standard, you can use Object.assign to merge two objects. See:

// Dados de entrada:
let data = [
    {"nome": "Carlos", "ativo": false},
    {"nome": "Joao", "ativo": false}
];

// Altera todos os objetos da lista:
data = data.map(obj => Object.assign(obj, {"ativo": true}));

// Exibe o resultado:
console.log(data);

If you do not want to use this method, you can make the change in the hand:

// Dados de entrada:
let data = [
    {"nome": "Carlos", "ativo": false},
    {"nome": "Joao", "ativo": false}
];

// Altera todos os objetos da lista:
data = data.map(obj => {
  obj.ativo = true;
  return obj;
});

// Exibe o resultado:
console.log(data);

A benchmark shows that doing the for directly is faster, followed by the second solution present here and finally the solution using the method assign. That is, you save some characters, but lose in efficiency. In this case, as it is simple, there is no reason not to use your own for.

  • But the map won’t be making a loop either?

  • @Alan in a way, yes. It only avoids you having to write it. Some languages can optimize the execution of map. I can’t tell if this is the case with Javascript.

Browser other questions tagged

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