Pregunta

Supongamos que tengo este código:

var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

Ahora, si quisiera eliminar " apellido "? .... ¿hay algún equivalente de
myArray [" apellido "]. remove () ?

(Necesito que el elemento desaparezca porque la cantidad de elementos es importante y quiero mantener las cosas limpias).

¿Fue útil?

Solución

Utilice el " eliminar " palabra clave en Javascript.

delete myArray["lastname"];

EDITAR:

En algunos motores de JavaScript, la palabra clave delete podría afectar el rendimiento ya que deshacerá la optimización de compilación / JIT.

http://www.html5rocks.com/en/tutorials/speed/v8 / http://www.smashingmagazine.com/2012/11/ escritura-memoria-rápida-eficiente-javascript /

Otros consejos

Todos los objetos en JavaScript se implementan como tablas hash / matrices asociativas. Entonces, los siguientes son equivalentes:

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

Y, como ya se indicó, usted " elimina " una propiedad de un objeto a través de la palabra clave delete , que puede usar de dos maneras:

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

Espero que la información adicional ayude ...

Ninguna de las respuestas anteriores aborda el hecho de que Javascript no tiene matrices asociativas para empezar: no hay ningún tipo array como tal, consulte typeof .

Lo que tiene Javascript son instancias de objetos con propiedades dinámicas. Cuando las propiedades se confunden con elementos de una instancia de objeto Array, entonces Bad Things & # 8482; están obligados a suceder:

Problema

var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log("number of elements: ", elements.length)   // returns 2
delete elements[1]
console.log("number of elements: ", elements.length)   // returns 2 (?!)

for (var i = 0; i < elements.length; i++)
{
   // uh-oh... throws a TypeError when i == 1
   elements[i].onmouseover = function () { window.alert("Over It.")}
   console.log("success at index: ", i)
}

Solución

Para tener una función de eliminación universal que no explote, use:

Object.prototype.removeItem = function (key) {
   if (!this.hasOwnProperty(key))
      return
   if (isNaN(parseInt(key)) || !(this instanceof Array))
      delete this[key]
   else
      this.splice(key, 1)
};

//
// Code sample.
//
var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log(elements.length)                        // returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop"))        // returns false as it should
console.log(elements.length)                        // returns 1 as it should

Eso solo elimina elimina el objeto pero aún mantiene la longitud de la matriz igual.

Para eliminar necesita hacer algo como:

array.splice(index, 1);

Si bien la respuesta aceptada es correcta, le falta la explicación de por qué funciona.

En primer lugar, su código debe reflejar el hecho de que esto es NO una matriz:

var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;

Tenga en cuenta que todos los objetos (incluidos Array s) se pueden usar de esta manera. Sin embargo, ¡no espere que las funciones estándar de matriz JS (pop, push, ...) funcionen en objetos!

Como se dijo en la respuesta aceptada, puede usar delete para eliminar las entradas de los objetos:

delete myObject["lastname"]

Debe decidir qué ruta desea tomar: use objetos (matrices / diccionarios asociativos) o use matrices (mapas). Nunca mezcle los dos.

Use el método splice para eliminar completamente el elemento de una matriz de objetos:

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");

Estás utilizando Object, no tienes una matriz asociativa para empezar. Con una matriz asociativa, agregar y eliminar elementos es así:

    Array.prototype.contains = function(obj) 
    {
        var i = this.length;
        while (i--) 
        {
            if (this[i] === obj) 
            {
                return true;
            }
        }
        return false;
    }


    Array.prototype.add = function(key, value) 
    {
        if(this.contains(key))
            this[key] = value;
        else
        {
            this.push(key);
            this[key] = value;
        }
    }


    Array.prototype.remove = function(key) 
    {
        for(var i = 0; i < this.length; ++i)
        {
            if(this[i] == key)
            {
                this.splice(i, 1);
                return;
            }
        }
    }



    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    }



    function ForwardAndHideVariables() {
        var dictParameters = getUrlVars();

        dictParameters.add("mno", "pqr");
        dictParameters.add("mno", "stfu");

        dictParameters.remove("mno");



        for(var i = 0; i < dictParameters.length; i++)
        {
            var key = dictParameters[i];
            var value = dictParameters[key];
            alert(key + "=" + value);
        }
        // And now forward with HTTP-POST
        aa_post_to_url("Default.aspx", dictParameters);
    }


    function aa_post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        //move the submit function to another variable
        //so that it doesn't get written over if a parameter name is 'submit'
        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var i = 0; i < params.length; i++)
        {
            var key = params[i];

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_(); //call the renamed function
    }

Como han señalado otras respuestas, lo que está utilizando no es una matriz de Javascript, sino un objeto de Javascript, que funciona casi como una matriz asociativa en otros idiomas, excepto que todas las claves se convierten en cadenas. El nuevo Map almacena las claves como su tipo original .

Si tuviera una matriz y no un objeto, podría usar la matriz . filter , para devolver una nueva matriz sin el elemento que desea eliminar:

var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
    return item !== 'Smith';
});

Si tiene un navegador más antiguo y jQuery, jQuery tiene un $ .grep método que funciona de manera similar:

myArray = $.grep(myArray, function(item) {
    return item !== 'Smith';
});

Hay una manera elegante en la Guía de estilo de Airbnb para hacer esto (ES7):

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

Copyright: https://codeburst.io / use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90

Si por alguna razón la tecla eliminar no funciona (como si no funcionara para yo)

Puede empalmarlo y luego filtrar los valores indefinidos

// to cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});

No intente encadenarlos ya que el empalme devuelve los elementos eliminados;

Puede eliminar una entrada de su mapa asignándola explícitamente a 'indefinido'. Como en su caso:

  

myArray [" lastname "] = undefined;

Es muy sencillo si tiene underscore.js dependencia en su proyecto -

_.omit(myArray, "lastname")

También podemos usarlo como una función. Angular arroja algún error si se usa como prototipo. Gracias @HarpyWar. Me ayudó a resolver un problema.

var removeItem = function (object, key, value) {
    if (value == undefined)
        return;

    for (var i in object) {
        if (object[i][key] == value) {
            object.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");

Al usar la palabra clave "delete" , eliminará el elemento de matriz de la matriz en javascript.

Por ejemplo,

Considere las siguientes declaraciones.

var arrayElementToDelete = new Object();

arrayElementToDelete["id"]           = "XERTYB00G1"; 
arrayElementToDelete["first_name"]   = "Employee_one";
arrayElementToDelete["status"]       = "Active"; 

delete arrayElementToDelete["status"];

La última línea del código eliminará el elemento de matriz cuya clave es " status " de la matriz.

var myArray = newmyArray = new Object(); 
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

var s = JSON.stringify(myArray);

s.replace(/"lastname[^,}]+,/g,'');
newmyArray = JSON.parse(p);

Sin bucles / iteraciones obtenemos el mismo resultado

Para " Arreglos " ;:

Si conoce el índice:

array.splice(index, 1);

Si conoce el valor:

function removeItem(array, value) {
    var index = array.indexOf(value);
    if (index > -1) {
        array.splice(index, 1);
    }
    return array;
}

La respuesta más votada para delete funciona bien en el caso de los objetos pero no para las matrices reales. Si uso delete , elimina elementos de los bucles pero mantiene el elemento como vacío y la longitud de la matriz no cambiará. Esto puede ser un problema en algunos escenarios.

Por ejemplo, si hago myArray.toString () en myArray después de eliminarlo mediante delete , crea una entrada vacía, es decir,

El único método de trabajo para mí:

function removeItem (array, value) {
    var i = 0;
    while (i < array.length) {
        if(array[i] === value) {
            array.splice(i, 1);
        } else {
            ++i;
        }
    }
    return array;
}

uso:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top