Suppose the following JSON:
{"id": 1, "preco": 100, "detalhe": "nenhum"}
If I build an array with 100 of these objects and want to remove the "detail" key from all, for example, is it possible (without being in the hand)?
Suppose the following JSON:
{"id": 1, "preco": 100, "detalhe": "nenhum"}
If I build an array with 100 of these objects and want to remove the "detail" key from all, for example, is it possible (without being in the hand)?
From ES6
you can use the Array.prototype.map()
using "Destructuring Assignment" along with " Spread syntax " to delete the attributes you want to remove:
const nova = lista.map(({ remover, ...outros }) => outros);
Applying to your example:
const lista = [
{"id": 1, "preco": 100, "detalhe": "nenhum"},
{"id": 2, "preco": 150, "detalhe": "todos"},
{"id": 3, "preco": 200, "detalhe": "alguns"},
];
const nova = lista.map(({ detalhe, ...demais }) => demais);
console.log('Original:', JSON.stringify(lista));
console.log('Resultado:', JSON.stringify(nova));
Assignment via destructuring assignment .
The destructuring assignment syntax is a JavaScript expression that enables you to extract data from arrays or objects into distinct variables.
var a, b, rest; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 [a, b, ...rest] = [1, 2, 3, 4, 5]; console.log(a); // 1 console.log(b); // 2 console.log(rest); // [3, 4, 5] ({a, b} = {a:1, b:2}); console.log(a); // 1 console.log(b); // 2
Spread syntax allows an iterative object such as an array expression or a string to be expanded where zero or more arguments (for function calls) or elements (for literal arrays) are expected, or an object is expanded where zero or more property: value pairs (for literal objects) are expected.
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // expected output: 6 console.log(sum.apply(null, numbers)); // expected output: 6
The map () method invokes the callback function passed by argument for each Array element and returns a new Array as a result.var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); // roots é [1, 2, 3], numbers ainda é [1, 4, 9]
In javascript you could do the following, assuming the following code:
let meuObjeto = {"id": 1, "preco": 100, "detalhe": "nenhum"}
delete meuObjeto.detalhe
Or
delete meuObjeto["detalhe"]
Now if you are a array with 100 of these objects, just do a repeat loop using one of the ways success is!
The following is an example, considering that meuArray
is a Array
with 100 objects of the type shown above.
meuArray.forEach(elemento => delete elemento.detalhe) // Ou da outra forma