Domanda

Supponiamo di avere questo codice:

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

Ora, se volessi rimuovere " cognome "? .... c'è qualche equivalente di
myArray [" cognome "]. Remove ()

?

(Ho bisogno che l'elemento sparisca perché il numero di elementi è importante e voglio mantenere le cose pulite.)

È stato utile?

Soluzione

Utilizza " elimina " parola chiave in Javascript.

delete myArray["lastname"];

EDIT:

In alcuni motori JavaScript, la parola chiave delete potrebbe compromettere le prestazioni poiché annullerà la compilazione / ottimizzazione JIT.

http://www.html5rocks.com/en/tutorials/speed/v8 / http://www.smashingmagazine.com/2012/11/ scrittura-fast-memoria-efficiente-javascript /

Altri suggerimenti

Tutti gli oggetti in JavaScript sono implementati come array hashtables / associativi. Quindi, i seguenti sono l'equivalente:

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

E, come già indicato, " rimuovi " una proprietà di un oggetto tramite la parola chiave delete , che puoi utilizzare in due modi:

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

Spero che le informazioni extra aiutino ...

Nessuna delle risposte precedenti affrontare il fatto che Javascript non ha array associativi per cominciare - non v'è alcuna array tipo in quanto tale, vedere typeof .

Ciò che Javascript ha, sono istanze di oggetti con proprietà dinamiche. Quando le proprietà sono confusi con elementi di un'istanza oggetto Array poi Bad Things & # 8482; sono destinati a succedere:

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)
}

Soluzione

Per avere una funzione di rimozione universale che non saltare in aria su di te, utilizzare:

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

Che rimuove solo elimina l'oggetto ma mantiene comunque la stessa lunghezza dell'array.

Per rimuovere devi fare qualcosa del tipo:

array.splice(index, 1);

Mentre la risposta accettata è corretta, manca la spiegazione del perché funziona.

Prima di tutto, il tuo codice dovrebbe riflettere il fatto che questo è NON un array:

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

Nota che tutti gli oggetti (incluso Array ) possono essere usati in questo modo. Tuttavia, non aspettarti che funzioni standard dell'array JS (pop, push, ...) funzionino sugli oggetti!

Come detto nella risposta accettata, è quindi possibile utilizzare elimina per rimuovere le voci dagli oggetti:

delete myObject["lastname"]

Dovresti decidere quale percorso vuoi prendere - usa gli oggetti (array / dizionari associativi) o usa gli array (mappe). Non mescolarli mai.

Usa il metodo splice per rimuovere completamente l'oggetto da un array di oggetti:

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");

Stai usando Object, per cominciare non hai un array associativo. Con un array associativo, l'aggiunta e la rimozione di elementi avviene in questo modo:

    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
    }

Come hanno notato altre risposte, quello che stai usando non è un array Javascript, ma un oggetto Javascript, che funziona quasi come un array associativo in altre lingue, tranne per il fatto che tutte le chiavi vengono convertite in stringhe. Il nuovo Map memorizza le chiavi come tipo originale .

Se avessi un array e non un oggetto, potresti usare l'array . filter , per restituire un nuovo array senza l'elemento che desideri rimuovere:

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

Se hai un browser e jQuery meno recenti, jQuery ha un $ .grep metodo che funziona in modo simile:

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

Esiste un modo elegante in Airbnb Style Guide per farlo (ES7):

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

Copyright: https://codeburst.io / usare-es2015-oggetto-resto-operatore-to-omettere-properties-38a3ecffe90

Se per qualsiasi motivo la chiave di eliminazione non funziona (come se non funzionasse io)

Puoi separarlo e quindi filtrare i valori non definiti

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

Non provare a incatenarli poiché la giunzione restituisce elementi rimossi;

Puoi rimuovere una voce dalla tua mappa assegnandola esplicitamente a "non definito". Come nel tuo caso:

  

myArray [" cognome "] = undefined;

È molto semplice se hai underscore.js dipendenza nel tuo progetto -

_.omit(myArray, "lastname")

Possiamo usarlo anche come funzione. Angular genera un errore se usato come prototipo. Grazie @HarpyWar. Mi ha aiutato a risolvere 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");

Usando la parola chiave "delete" , eliminerà l'elemento dell'array dall'array in javascript.

Ad esempio,

Prendi in considerazione le seguenti dichiarazioni.

var arrayElementToDelete = new Object();

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

delete arrayElementToDelete["status"];

L'ultima riga del codice rimuoverà l'elemento dell'array la cui chiave è " status " dall'array.

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);

Senza loop / iterate otteniamo lo stesso risultato

Per " Array " ;:

Se conosci l'indice:

array.splice(index, 1);

Se conosci il valore:

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

La risposta più votata per delete funziona bene in caso di oggetti ma non per le vere matrici. Se uso elimina rimuove gli elementi dai loop ma mantiene l'elemento come vuoto e la lunghezza dell'array non cambierà. Questo può essere un problema in alcuni scenari.

Ad esempio, se eseguo myArray.toString () su myArray dopo la rimozione tramite elimina crea una voce vuota, ad esempio ,,

L'unico metodo di lavoro per me:

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

utilizzo:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top