如何从 JavaScript 关联数组中删除对象?

发布于 2024-07-10 01:53:42 字数 275 浏览 9 评论 0原文

假设我有这样的代码:

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

现在如果我想删除“lastname”?....是否有相当于 myArray["lastname"].remove()

(我需要去掉元素,因为元素的数量很重要,而且我想保持干净。)

Suppose I have this code:

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

Now if I wanted to remove "lastname"?....is there some equivalent of
myArray["lastname"].remove()?

(I need the element gone because the number of elements is important and I want to keep things clean.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

長街聽風 2024-07-17 01:53:42

JavaScript 中的对象可以被视为关联数组,将键(属性)映射到值。

要从 JavaScript 中的对象中删除属性,您可以使用 < code>delete 运算符:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

请注意,当 delete 应用于 Array,您将创建一个 稀疏填充数组(即缺少索引的数组)。

在使用 Array 实例时,如果您不想创建稀疏填充的数组(而且您通常不会这样做),那么您应该使用 Array#spliceArray#pop

请注意,JavaScript 中的delete 运算符不会直接释放内存。 其目的是从对象中删除属性。 当然,如果被删除的属性保留了对对象 o 的唯一剩余引用,则 o 随后将以正常方式被垃圾收集。

使用 delete 运算符可能会影响 JavaScript 引擎优化<的能力/a> 代码

Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.

To remove a property from an object in JavaScript you use the delete operator:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).

When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.

Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.

Using the delete operator can affect JavaScript engines' ability to optimise code.

○闲身 2024-07-17 01:53:42

JavaScript 中的所有对象都被实现为哈希表/关联数组。 因此,以下内容是等效的:

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

并且,如前所述,您可以通过 delete 关键字从对象中“删除”属性,您可以通过两种方式使用该属性:

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

希望额外的信息有帮助.. 。

All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:

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

And, as already indicated, you "remove" a property from an object via the delete keyword, which you can use in two ways:

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

Hope the extra info helps...

我还不会笑 2024-07-17 01:53:42

前面的答案都没有解决 JavaScript 没有关联数组的事实 - 没有这样的 array 类型,请参阅 typeof

JavaScript 拥有的是具有动态属性的对象实例。 当属性与 Array 对象实例的元素混淆时,必然会发生 Bad Things™:

问题

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

解决方案

要拥有一个不会让您崩溃的通用删除函数,请使用:

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

None of the previous answers address the fact that JavaScript does not have associative arrays to begin with - there is no array type as such, see typeof.

What JavaScript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Things™ are bound to happen:

Problem

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

Solution

To have a universal removal function that does not blow up on you, 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
柏林苍穹下 2024-07-17 01:53:42

这只会删除对象,但仍保持数组长度相同。

要从数组中删除元素,您需要执行以下操作:

array.splice(index, 1);

That only deletes the object, but it still keeps the array length the same.

To remove the element from the array, you need to do something like:

array.splice(index, 1);
裂开嘴轻声笑有多痛 2024-07-17 01:53:42

虽然接受的答案是正确的,但它缺少对其工作原理的解释。

首先,您的代码应该反映这样一个事实:这不是数组:

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

请注意,所有对象(包括Array)都可以这样使用。 但是,不要指望标准 JavaScript 数组函数(pop、push 等)能够作用于对象!

正如接受的答案中所述,然后您可以使用 delete 从对象中删除条目:

delete myObject["lastname"]

您应该决定您希望采取的路线 - 要么使用对象(关联数组/字典)或使用数组(地图) 。 切勿将两者混用。

While the accepted answer is correct, it is missing the explanation why it works.

First of all, your code should reflect the fact that this is not an array:

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

Note that all objects (including Arrays) can be used this way. However, do not expect for standard JavaScript array functions (pop, push, etc.) to work on objects!

As said in accepted answer, you can then use delete to remove the entries from objects:

delete myObject["lastname"]

You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.

一身软味 2024-07-17 01:53:42

Airbnb 风格指南中有一种优雅的方法可以做到这一点 (ECMAScript 7):

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

版权所有:https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90

There is an elegant way in the Airbnb Style Guide to do this (ECMAScript 7):

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

倾城泪 2024-07-17 01:53:42

正如其他答案所指出的,您使用的不是 JavaScript 数组,而是 JavaScript 对象,它的工作方式几乎类似于其他语言中的关联数组,只不过所有键都转换为字符串。 新的 Map 将密钥存储为原始密钥类型。

如果您有一个数组而不是一个对象,则可以使用数组的 .filter 函数,返回一个新数组,其中不包含要删除的项目:

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

如果您有较旧的浏览器和 jQuery,则 jQuery 有一个 $.grep 方法的工作原理类似:

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

As other answers have noted, you are not using a JavaScript array, but a JavaScript object, which works almost like an associative array in other languages except that all keys are converted to strings. The new Map stores keys as their original type.

If you had an array and not an object, you could use the array's .filter function, to return a new array without the item you want removed:

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

If you have an older browser and jQuery, jQuery has a $.grep method that works similarly:

myArray = $.grep(myArray, function(item) {
    return item !== 'Smith';
});
掩于岁月 2024-07-17 01:53:42

如果您想要更实用、更优雅的方法,可以执行以下操作:

const o = { firstName: "foo", lastName: "bar" };
const { lastName, ...removed } = o;
lastName // bar
removed // { firstName: "foo" }

请注意,如果对象中没有剩余项目,则 removed 的值将是未定义的。

You can do the following if you want a more functional and elegant approach:

const o = { firstName: "foo", lastName: "bar" };
const { lastName, ...removed } = o;
lastName // bar
removed // { firstName: "foo" }

Note that the value of removed will be undefined if there are no items left in the object.

Smile简单爱 2024-07-17 01:53:42

通过使用“delete”关键字,它将从JavaScript中的数组中删除数组元素。

例如,

考虑以下陈述。

var arrayElementToDelete = new Object();

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

delete arrayElementToDelete["status"];

代码的最后一行将从数组中删除键为“status”的数组元素。

By using the "delete" keyword, it will delete the array element from array in JavaScript.

For example,

Consider following statements.

var arrayElementToDelete = new Object();

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

delete arrayElementToDelete["status"];

The last line of the code will remove the array element whose key is "status" from the array.

葵雨 2024-07-17 01:53:42

使用方法 splice 可以从对象数组中完全删除一个项目:

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

Use method splice to completely remove an item from an object array:

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");
地狱即天堂 2024-07-17 01:53:42

对于“数组”:

如果您知道索引:

array.splice(index, 1);

如果您知道值:

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

对于删除,得票最多的答案在对象的情况下效果很好但不适用于真正的数组。 如果我使用delete,它会从循环中删除元素,但将元素保留为,并且数组的长度不会改变。 在某些情况下这可能会出现问题。

例如,如果我在通过 delete 删除后对 myArray 执行 myArray.toString(),它会创建一个空条目,即 ,,

For "Arrays":

If you know the index:

array.splice(index, 1);

If you know the value:

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

The most upvoted answer for delete works well in case of objects but not for the real arrays. If I use delete it removes elements from loops but keeps the element as empty and length of array wont change. This may be a problem in some scenarios.

For example, if I do myArray.toString() on myArray after removal via delete, it creates an empty entry, i.e. ,,.

情栀口红 2024-07-17 01:53:42

如果您的项目中有 Underscore.js 依赖项,那就非常简单了 -

_.omit(myArray, "lastname")

It's very straightforward if you have an Underscore.js dependency in your project -

_.omit(myArray, "lastname")
夏末 2024-07-17 01:53:42

对我来说唯一的工作方法:

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

用法:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]

The only working method for me:

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

Usage:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]
み零 2024-07-17 01:53:42

如果出于某种原因,删除键不起作用(就像它对我不起作用一样),您可以将其拼接出来,然后过滤未定义的值:

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

不要尝试链接它们,因为拼接返回删除的元素;

If, for whatever reason, the delete key is not working (like it wasn't working for me), you can splice it out and then filter the undefined values:

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

Don’t try and chain them since splice returns removed elements;

拍不死你 2024-07-17 01:53:42

您可以通过显式将条目指定为“未定义”来从地图中删除条目。 就像你的情况一样:

myArray["姓氏"] = 未定义;

You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:

myArray["lastname"] = undefined;

行雁书 2024-07-17 01:53:42

我们也可以将它用作函数。 如果用作原型,Angular 会引发一些错误。 谢谢@HarpyWar。 它帮助我解决了一个问题。

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

We can use it as a function too. Angular throws some error if used as a prototype. Thanks @HarpyWar. It helped me solve a problem.

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");
記柔刀 2024-07-17 01:53:42

您正在使用对象,并且一开始就没有关联数组。 对于关联数组,添加和删除项目如下所示:

    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
    }

You are using Object, and you don't have an associative array to begin with. With an associative array, adding and removing items goes like this:

    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
    }
金橙橙 2024-07-17 01:53:42
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);

没有循环/迭代我们得到相同的结果。

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

Without looping/iterates we get the same result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文