How to remove a Key from a JSON

Asked

Viewed 3,839 times

6

Suppose the following JSON:

{"id": 1, "preco": 100, "detalhe": "nenhum"}

If I build an array with 100 of these objects and want to take the "detail" key from everyone, for example, it is possible (without being at hand)?

2 answers

7


From the ES6 you can use the function Array.prototype.map() using "Assignment via structuring (destructuring assignment)" together with the "Scattering Syntax (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 structuring (destructuring assignment).

The syntax of assignment via structuring (destructuring assignment) is a Javascript expression that allows you to extract data from arrays or objects in different 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

Scattering Syntax (Spread syntax).

Scattering Syntax (Spread syntax) allows an iterable 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 to be expanded where zero or more pairs property:value (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

Array.prototype.map().

The map() method invokes the callback function passed by argument to 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]
  • 1

    Very interesting, even though I know the map and the operador spread i had never used them that way! Thanks for the info.

4

In javascript you could do it as follows, assuming the following code:

let meuObjeto = {"id": 1, "preco": 100, "detalhe": "nenhum"}

delete meuObjeto.detalhe

Or

delete meuObjeto["detalhe"]

Now if you’re one array with 100 of these objects is just to make a loop of repetition using one of the shapes that is successful!

An example is given below, considering that the meuArray is a Array with 100 objects of the type shown above.

meuArray.forEach(elemento => delete elemento.detalhe) // Ou da outra forma

Browser other questions tagged

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