How do I set an equal value for a property of an object on all objects in a list?

1

How do I set a value for a property in all indexes in the list without looping?

object:

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

list:

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

In this example, all people 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 this loop, make this change all at once? because in the actual application the object is more complex and has many records, leaving this method slow.

    
asked by anonymous 24.05.2017 / 22:28

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 at 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 simple benchmark shows that doing for directly is faster, followed by the second solution, and finally the solution using the assign method. That is, you save some characters, but lose in efficiency. In this case, as it is simple, there is no reason not to use for itself.

    
24.05.2017 / 22:51