How to delete Object Property without knowing its Key. JavaScript

0

This time I have a question, I have this example object:

"pasada" : {
    "09-10" : 34.11,
    "09-11" : 35.73,
    "09-12" : 34.03,
    "09-13" : 35.85,
    "09-14" : 38.75,
    "09-15" : 34.07,
    "09-16" : 32.46,
    "09-17" : 34.57
}

Which your key: valor will always change and you could not know what key you could do to delete the last element in this case "09-17" or the first one that would be "09-10" depending on my requirement.

I appreciate the help you can give me!

    
asked by Gabriela 17.09.2018 в 17:43
source

2 answers

8

What you can do is get the keys of your object and then delete them according to the index that you want, for example the first key (index: 0), the third (index: 2), etc.

var pasada = {
             "09-10" : 34.11,
             "09-11" : 35.73,
             "09-12" : 34.03,
             "09-13" : 35.85,
             "09-14" : 38.75,
             "09-15" : 34.07,
             "09-16" : 32.46,
             "09-17" : 34.57
              };
              
var keys = Object.keys(pasada);
var indexKeyToDelete = 0;

console.log("El objeto con todas las keys:");
console.log(pasada);

// Equivale a "delete pasada.NombreDeLaKey" o "delete pasada["NombreDeLaKey"]"
delete pasada[keys[indexKeyToDelete]];

console.log("El objeto con la key borrada:");
console.log(pasada);

Additional information:

  

Object.keys returns an array whose elements are strings   corresponding to the enumerable properties that are found   directly on the object.

     

The delete operator removes a property from an object.

    
answered by 17.09.2018 / 17:56
source
5

You can get the keys like this:

var llaves = Object.keys(pasada);

As a result I would give you an arrangement:

[09-10, 09-11, ... ]

Now that you have the keys you can play whatever you want

var llave = llaves[0]; // Es la primera

var llave = llaves[llaves.length - 1]; // es la ultima

And you can occupy this arrangement to make an indeterminate number of combinations.

  • Get the pairs or odd
  • Get the ones that start on 9
  • etc.

Now that you know the key, just erase it

delete pasada[llave];
    
answered by 17.09.2018 в 17:58