如何从javascript对象中删除属性?

How do I remove a property from a JavaScript object?

假设我创建一个对象如下:

1
2
3
4
5
var myObject = {
   "ircEvent":"PRIVMSG",
   "method":"newURI",
   "regex":"^http://.*"
};

移除财产regex的最佳方法是什么,以如下所示的新myObject结束?

1
2
3
4
var myObject = {
   "ircEvent":"PRIVMSG",
   "method":"newURI"
};


这样地:

1
2
3
4
5
6
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop ="regex";
delete myObject[prop];

演示

1
2
3
4
5
6
7
8
var myObject = {
   "ircEvent":"PRIVMSG",
   "method":"newURI",
   "regex":"^http://.*"
};
delete myObject.regex;

console.log(myObject);

对于任何有兴趣阅读更多内容的人来说,Stack Overflow用户Kangax在他们的博客上写了一篇关于delete声明的非常深入的博客文章,Understanding Delete。强烈推荐。


运营商是unexpectedly delete慢!

看的基准。

唯一的真正的方式来删除是删除对象的属性没有任何食物,但它的作品~100倍慢。相对于它的"另类",object[key] = undefined设置。

这是不正确的答案选择的这一问题。但是,如果你使用它与关怀,你可以dramatically速度设置的一些算法。如果你是在和你有delete环使用性能的问题进行详细的解释,阅读。

当一个delete应该使用到undefined当集值吗?

一个对象可以被看见的一组关键值对。我的电话是原始值或参考其他对象的连接,这是关键。

当你使用delete,传递的结果是对象的代码,如果你不有一个在线控制(或当你不确定什么是你的团队或个人)。

它的重点从deletes HashMap。

1
2
3
4
 var obj = {
     field: 1    
 };
 delete obj.field;

使用单位对undefined,当你关心的性能。它可以让你的代码的重要助力。

其最关键的地方是在线的HashMap,仅是与undefined替换值。我认为,这将仍然iterate for..in环上的关键。

1
2
3
4
 var obj = {
     field: 1    
 };
 obj.field = undefined;

使用这种方法,所有的方式,不存在将决定房地产学院工作的预期。

然而,这样的代码:

object.field === undefined

将两个equivalently是常用的方法。

试验

对summarize,差异是所有关于房地产的存在方式决定),和关于for..in环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 console.log('* ->"Takes prototype inheritance into consideration, that means it lookups all over prototype chain too."');

 console.log(obj.field === undefined, 'obj.field === undefined', 'You get"undefined" value when querying for"field" in object-hashmap. *');

 console.log(obj["field"] === undefined, 'obj["field"] === undefined', 'Just another way to query (equivalent). *');

 console.log(typeof obj.field ==="undefined", 'typeof obj.field ==="undefined"', 'Get the value attached to"field" key, and check it\'s type is"undefined". *');

 console.log("field" in obj, '"field" in obj', 'This statement returns true if"field" key exists in the hashmap. False otherwise. *');

 console.log(obj.hasOwnProperty("field"), 'obj.hasOwnProperty("field")', 'This statement returns true if \'field\' key exists in the hashmap. The ONLY way NOT to lookup for property in the prototype chain!');
 //Object.keys().indexOf() is an overkill that runs much slower :)

 var counter = 0,
     key;
 for (key in obj) {
     counter++;
 }
 console.assert(counter === 0, 'counter === 0', '"field" is not iterated using"for .. in" loop. *');

小心内存泄漏!

在以更快的obj[prop] = undefined是另一个重要的考虑delete obj[prop]不做,那是不可能obj[prop] = undefined永远是适当的。从delete obj[prop]removes propobj和erases可以从内存,而obj[prop] = undefined集值prop到内存中的prop仍然undefined这叶。因此,在许多情况下,有人创建和删除键,使用昂贵的记忆能力obj[prop] = undefined和解(造成的页面到封冻)和一外潜在的内存错误。看看下面的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"use strict";
var theNodeList=[], i, current, numberOfNodes=65536, body=document.body, nodeRecords=[];
for (i = 0; i !== numberOfNodes; i++) {
    nodeRecords[i] = [];
    current = theNodeList[i] = document.createElement("div");
    current.textContent = i;
    document.body.appendChild( current );
}
var lastTime = -1;
requestAnimationFrame(function recordUpdates(){
    var currentTime = Math.round( performance.now()*1000 )
    for (i = 0; i !== numberOfNodes; i++) {
        if (lastTime !== -1) {
            // the previously collected data is no longer in use
            /*************************************************/
            /****/ nodeRecords[i][lastTime] = undefined; /****/
            /*************************************************/
        }
        nodeRecords[i][currentTime] = theNodeList[i].outerHTML;
    }
    lastTime = currentTime;
    requestAnimationFrame( recordUpdates );
});

在代码上做简单的nodeRecords[i][lastTime] = undefined;,会使大量内存泄漏,因为每个动画帧。每一帧,都将弹出一个65536个DOM元素的65536个人槽槽前,但只会是65536个叶集未挂在他们的记忆。试着去吧,以上的代码运行在控制台的个人和企业。强迫一个后外存储器来运行它再次尝试错误,除非与以下的版本的代码,而不是使用delete算子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"use strict";
var theNodeList=[], i, current, numberOfNodes=65536, body=document.body, nodeRecords=[];
for (i = 0; i !== numberOfNodes; i++) {
    nodeRecords[i] = [];
    current = theNodeList[i] = document.createElement("div");
    current.textContent = i;
    document.body.appendChild( current );
}
var lastTime = -1;
requestAnimationFrame(function recordUpdates(){
    var currentTime = Math.round( performance.now()*1000 )
    for (i = 0; i !== numberOfNodes; i++) {
        if (lastTime !== -1) {
            // the previously collected data is no longer in use
            /********************************************/
            /****/ delete nodeRecords[i][lastTime]; /****/
            /********************************************/
        }
        nodeRecords[i][currentTime] = theNodeList[i].outerHTML;
    }
    lastTime = currentTime;
    requestAnimationFrame( recordUpdates );
});

上述代码片断中所看到的,有一些罕见的病例delete适当使用的运营商。然而,不太担心这个问题。这只会成为问题的对象是具有长lifespan不断得到新的键添加到他们。在任何其他情况(这是几乎每一个真实世界的案例中,它是最合适的编程)obj[prop] = undefined使用。这一部分主要的目的是把你的注意力到一只这样的稀有的机会,这不成为问题,然后你可以在你的代码更容易理解,因此在问题没有浪费你的时间dissecting码估计和理解这个问题。

不要总是对undefined

这是一个JavaScript方面的考虑是重要的多态性。当assigning多态性是相同的变量/槽中的不同类型的对象上看到的一段。

1
2
3
4
5
6
var foo ="str";
foo = 100;          // variable foo is now labeled polymorphic by the browser
var bar = ["Some","example"];
bar[2] ="text";    // bar is a monomorphic array here because all its entries have the
                    // same type: string primitive
bar[1] = undefined; // bar is now a polymorphic array

然而,有两个主要问题:unfixable与阵列

  • 它们速度慢,内存效率低。当访问一个特定的索引时,浏览器不只是获取数组的全局类型,而是根据每个索引获取类型,每个索引存储其类型的额外元数据。
  • 一旦是多态的,总是多态的。当数组变为多态时,在WebKit浏览器中多态性不能撤消。因此,即使将多态数组恢复为非多态数组,浏览器仍然会将其存储为多态数组。
  • 人们可以把多态性比作药物成瘾。乍一看,它似乎利润丰厚:漂亮的、毛绒绒绒的代码。然后,编码人员将他们的阵列引入多态性药物。立刻,多态数组的效率就降低了,而且由于被下药,它再也不能像以前那样有效了。为了将这种情况与现实生活联系起来,吸食可卡因的人甚至可能无法操作一个简单的门把手,更不用说能够计算圆周率的数字了。同样,多态性药物的阵列也不能像单态阵列那样有效。好的。

    但是,药物中毒的类比与delete手术有什么关系?答案包含在上面代码片段的最后一行代码中。因此,让我们重新检查一下,这次要扭转一下。好的。

    1
    2
    3
    4
    5
    var bar = ["Some","example"];
    bar[2] ="text";    // bar is not a polymorphic array here because all its entries have the
                        // same type: string primitive
    bar[1] ="";        // bar is still a monomorphic array
    bar[1] = undefined; // bar is now a polymorphic array

    观察。bar[1] =""不强制多态性,而bar[1] = undefined则强制多态性。因此,在可能的情况下,应始终为其对象使用相应的类型,以免意外导致多态性。一个这样的人可以使用下面的列表作为一般参考,以使他们去。但是,请不要明确使用以下想法。相反,使用任何对代码有效的方法。好的。

    • 当使用类型化为布尔原语的数组/变量时,使用falseundefined作为空值。虽然避免不必要的多态性是很好的,但是重写所有代码以明确地禁止它实际上可能会导致性能下降。使用共同的判断!
    • 当对数字原语使用类型化的数组/变量时,使用0作为空值。注意,在内部,有两种类型的数字:快速整数(2147483647到-2147483648包括在内)和慢速浮点双精度(除NaNInfinity以外的任何数字)。当一个整数降级为double时,它将无法提升回整数。
    • 当对字符串原语使用类型化的数组/变量时,使用""作为空值。
    • 使用符号时,等等,为什么要使用符号????!符号对性能不好。所有编程为使用符号的东西都可以重新编程为不使用符号,从而在没有符号的情况下产生更快的代码。符号实际上只是超低效的元糖。
    • 当使用其他任何东西时,请使用null

    但是,要留心!现在不要突然开始对所有先前存在的代码执行此操作,因为它可能会破坏这些先前存在的代码和/或引入奇怪的错误。相反,这样一个有效的实践需要从一开始就实施,并且在转换以前存在的代码时,建议您对所有与之相关的行进行双重、三重、四重检查,因为尝试将旧代码升级到这个新的实践可能是有风险的,也可能是有回报的。好的。好啊。


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    var myObject = {"ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*
    <hr>
    <p>
    Update 2018-07-21: For a long time, I have felt embarrassed about this answer, so I think it's time that I touch it up a little bit. Just a little commentary, clarification, and formatting to help expedite the reading of the needlessly long and convoluted parts of this answer.
    </p>



    THE SHORT VERSION

    The actual answer to the question

    <p>
    As others have said, you can use <wyn>delete</wyn>.
    </p>

    [cc lang="
    javascript"]obj // {"foo":"bar
    <div class="suo-content">[collapse title=""]<ul><li>不过,这个<wyn>delete</wyn>关键字要方便得多,lol</li><li>此方法不会修改可能仍在其他地方引用的原始对象。这可能是一个问题,也可能不是一个问题,这取决于它是如何使用的,但这是需要记住的。</li><li>@b1kmusic以下是从数组中删除元素的方法:拼接</li><li>@wulftone不,它拆分数组,不删除值。我真的认为从需要删除特定值的数组中删除的最佳方法是使用<wyn>delete</wyn>并生成垃圾收集函数来清理它。</li><li>@我误解了。我认为"删除"是指"从数组中删除",实际上是指同时从数组和内存中删除,对吗?</li><li>@伍尔夫顿,嗯,这就是我所认为的删除一般意义上的意思。是的,对于我的一些应用程序,我遇到了一些奇怪的小故障,这些小故障是由仅使用<wyn>delete array[index]</wyn>引起的,我必须编写自己的垃圾收集方法来保持数组的整洁,这样就不会使本地存储区混乱/跳过一个数字。</li><li>@伍尔夫通我确实找到了一个用于<wyn>Array.prototype.splice()</wyn>的用途。我给了我的答案一个非常需要的更新</li><li>我在你的编辑中没有看到<wyn>splice</wyn>,但<wyn>remove</wyn>应该是<wyn>Array.prototype.remove = function(index) { this.splice(index, 1); };</wyn></li><li>@是的,那将是一种更聪明的方法。在重写的时候,我才刚刚开始了解<wyn>splice()</wyn></li><li><wyn>array.splice(index, 1)</wyn>……</li><li>但是,定义<wyn>Array.prototype.remove()</wyn>可能比定义这两个整数所需的大约8个字节要多。</li><li>@patrickroberts javascript的数字类型定义为64位双精度,那么它不是16字节吗?</li><li>@Bradenbest好的,当然,16字节。我相信记忆中的功能还是比较大的。</li><li>@帕特里克罗伯茨,这是一个愚蠢的,做作的场景。在关于对象的问题中讨论数组的追溯性借口。</li><li>这篇文章充满了牛1。它不能解决这个问题!2。这是对语言滥用的一个例证,也是对"它不起作用"的抱怨。三。不要因为crockford为空数组索引放入null的特殊错误而责备javascript删除操作符。他不明白"无效"的意思——他认为这是个错误。错误是他自己造成的,而且是唯一的——给定数组索引的已删除值中没有空值。数组中没有"孔"——这是一个空索引。绝对合法和预期的。</li><li>合法的,预期的,但不一定是想要的,因此我为什么要检查拼接函数。我不怪任何事。我要指出的是,删除的结果可能并不总是你所认为的那样,这是JavaScript许多不太合理的特性之一。</li><li>在数组中保留一个空值本身并不是不合逻辑的。但是,在像JS这样的动态语言中,数组在技术上是对象,可以很容易地调整大小和修改,您会认为删除操作会将其拼接出来或抛出一个错误。在C语言中,将值保留为sentinel。</li><li>而且,你说得对,我没有直接回答这个问题。然而,这仍然是有用的信息。与注释格式不兼容的有用信息。因此,为什么将其作为答案发布。</li><li>在阵列上,您可以使用正确控制阵列的<wyn>array.splice()</wyn></li><li>@你应该读完整的答案。具体来说,实施<wyn>Array.prototype.remove</wyn></li><li>@Bradenbest,你是对的,但问题是要删除对象属性,而不是数组项。数组实际上是为添加和删除属性而创建的,并具有相应的API。对象没有,因此使用<wyn>delete</wyn>将是这个问题的最佳答案。</li><li>@E730旧消息。这已经在评论中讨论过了。事实上,差不多一年前。</li></ul>[/collapse]</div><p><center>[wp_ad_camp_1]</center></p><hr>
    <p>
    Old question, modern answer. Using object destructuring, an ECMAScript&nbsp;6 feature, it's as simple as:
    </p>

    [cc lang="javascript"]const { a, ...rest } = { a: 1, b: 2, c: 3 };

    或者用问题样本:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    const myObject = {"ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*
    <div class="
    suo-content">[collapse title=""]<ul><li>可能是因为目标是从对象中删除一个属性,而不是创建一个没有该属性的新属性…不过,你的解决方案是我最喜欢的,因为我喜欢不变的方式。</li><li>问题是"以新的MyObject结束"。</li><li>根据kangax.github.io/compat-table/esnext,ES6的对象REST属性没有最终确定,没有浏览器实现,只有babel提供支持。</li><li>另外,我认为这种方法比某些替代方法更不可读。这基本上是一种利用析构化赋值和rest运算符来实现对读者来说不明显的东西的黑客行为。相比之下,delete语句或下划线方式uuuomit在意图方面都非常明显。</li><li>另外,在本例中,您使用regex变量丢弃了您的作用域。</li><li>为删除属性添加下划线会破坏您的项目:)您也可以将其分配给任何其他变量,例如<wyn>_</wyn>,例如go to discard a result:<wyn>const { regex: _, ...newObject } = myObject;</wyn>等语言中使用的变量。</li><li>这实际上是一个很好的一行程序,用于新的对象分配而不需要不必要的道具,并且已经得到node.js 8.*/9.*和<wyn>--harmony</wyn>的支持:node.green/&hellip;</li><li>如果regex是保存键的变量怎么办?</li><li>@pranaykumar我希望这个语法可以工作;<wyn>const { [key], ...newObject } = myObject;</wyn>,但是它不能工作,所以我认为它不可能被销毁。</li><li>使用<wyn>freeze()</wyn>d和<wyn>seal()</wyn>d对象,您不能简单地将<wyn>delete</wyn>作为一个属性。所以这是一个很好的选择。尽管在大多数情况下,从冻结/密封对象中删除属性可能是没有意义的,考虑到关键是要对您的数据结构做出某些保证,而这种模式将破坏这些数据结构。对于那些需要非破坏性地欺骗一个对象但没有其某些属性的情况,这是完美的。</li><li>这将创建一个全新的对象,请注意,这将破坏继承、instanceof运算符。</li></ul>[/collapse]</div><hr>
    <p>
    Another alternative is to use the Underscore.js library.
    </p>

    <p>
    Note that <wyn>_.pick()</wyn> and <wyn>_.omit()</wyn> both return a copy of the object and don't directly modify the original object. Assigning the result to the original object should do the trick (not shown).
    </p>

    <p>
    Reference: link _.pick(object, *keys)
    </p>

    <p>
    Return a copy of the object, filtered to only have values for the
    whitelisted keys (or array of valid keys).
    </p>

    [cc lang="
    javascript"]var myJSONObject =
    {"
    ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*
    <div class="suo-content">[collapse title=""]<ul><li>记住,如果对象的键是数字,则可能需要<wyn>_.omit(collection, key.toString())</wyn></li><li>嗯…下划线比<wyn>delete obj[prop]</wyn>慢约100倍,比<wyn>obj[prop] = undefined</wyn>慢约100倍。</li></ul>[/collapse]</div><hr>扩展语法(ES6)<P>给任何需要它的人…</P><P>若要在此线程中完成@koen answer,如果要使用排列语法删除动态变量,可以这样做:</P>[cc lang="javascript"]const key = 'a';

    const { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 };

    console.log(rest); // { b: 2, c: 3 }

    *foo将是一个新变量,值为a(即1)。

    < BR>更新:
    从对象中删除属性的常见方法很少。
    每个方法都有自己的优缺点(请检查此性能比较):

    删除运算符
    但是,如果您在大量对象上操作,因为它的性能没有得到优化,那么它可能不是最佳选择。

    1
    delete obj[key];

    < BR>重新分配
    delete快2倍以上,但是属性不会被删除,可以迭代。

    1
    2
    3
    obj[key] = null;
    obj[key] = false;
    obj[key] = undefined;

    < BR>排列运算符
    这个ES6操作符允许我们返回一个全新的对象,不包括任何属性,而不改变现有对象。缺点是,它的性能比上面提到的差,当您一次需要删除许多属性时,不建议使用它。

    1
    { [key]: val, ...rest } = obj;


    The term you have used in your question title Remove a property from a JavaScript object, can be interpreted in some different ways. The one is to remove it for whole the memory and the list of object keys or the other is just to remove it from your object. As it has been mentioned in some other answers, the delete keyword is the main part. Let's say you have your object like:

    1
    2
    myJSONObject = {"ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*
    <div class="
    suo-content">[collapse title=""]<ul><li>你错了-在javascript中,只有对象是通过引用传递的,所以如果<wyn>myJSONObject.regex</wyn>的值是一个字符串,并且你将它赋给其他对象,那么其他对象就有这个值的副本。</li><li>你是对的,这是一句名言:"小心你对同一对象的其他引用。"</li></ul>[/collapse]</div><hr><P>ECMAScript 2015(或ES6)带有内置反射对象。可以通过调用以目标对象和属性键为参数的reflect.delete property()函数来删除对象属性:</P>[cc lang="javascript"]Reflect.deleteProperty(myJSONObject, 'regex');

    相当于:

    1
    delete myJSONObject['regex'];

    但是,如果对象的属性不可配置,则既不能使用delete property函数也不能使用delete运算符删除它:

    1
    2
    3
    4
    let obj = Object.freeze({ prop:"value" });
    let success = Reflect.deleteProperty(obj,"prop");
    console.log(success); // false
    console.log(obj.prop); // value

    object.freeze()使对象的所有属性都不可配置(除其他之外)。deleteProperty函数(以及delete运算符)在尝试删除其任何属性时返回false。如果属性是可配置的,则返回true,即使属性不存在。

    deletedeleteProperty的区别在于使用严格模式时:

    1
    2
    3
    4
    5
    6
    "use strict";

    let obj = Object.freeze({ prop:"value" });
    Reflect.deleteProperty(obj,"prop"); // false
    delete obj["prop"];
    // TypeError: property"prop" is non-configurable and can't be deleted


    假设您有一个像这样的对象:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var Hogwarts = {
        staff : [
            'Argus Filch',
            'Filius Flitwick',
            'Gilderoy Lockhart',
            'Minerva McGonagall',
            'Poppy Pomfrey',
            ...
        ],
        students : [
            'Hannah Abbott',
            'Katie Bell',
            'Susan Bones',
            'Terry Boot',
            'Lavender Brown',
            ...
        ]
    };

    删除对象属性

    如果要使用整个staff数组,正确的方法是:

    1
    delete Hogwarts.staff;

    或者,您也可以这样做:

    1
    delete Hogwarts['staff'];

    同样,通过调用delete Hogwarts.students;delete Hogwarts['students'];来删除整个学生数组。

    删除数组索引

    现在,如果您想删除一个工作人员或学生,这个过程有点不同,因为这两个属性都是数组本身。

    如果你知道你的员工的索引,你可以简单地做到:

    1
    Hogwarts.staff.splice(3, 1);

    如果您不知道索引,还必须进行索引搜索:

    1
    Hogwarts.staff.splice(Hogwarts.staff.indexOf('Minerva McGonnagall') - 1, 1);

    注释

    虽然从技术上讲,您可以将delete用于数组,但在稍后调用(例如Hogwarts.staff.length)时,使用它会导致不正确的结果。换句话说,delete将删除元素,但不会更新length属性的值。使用delete也会破坏索引。

    因此,当从一个对象中删除值时,首先要考虑是处理对象属性还是处理数组值,并基于此选择适当的策略。

    如果你想试验这个,你可以用这个小提琴作为起点。


    The delete operator is the best way to do so.

    A live example to show:

    1
    2
    3
    var foo = {bar: 'bar'};
    delete foo.bar;
    console.log('bar' in foo); // Logs false, because bar was deleted from foo.


    我个人使用underline.js或lodash进行对象和数组操作:

    1
    myObject = _.omit(myObject, 'regex');

    根据MDN描述,使用delete方法是最好的方法,delete操作符从对象中移除属性。所以你可以简单地写:

    1
    2
    3
    delete myObject.regex;
    // OR
    delete myObject['regex'];

    The delete operator removes a given property from an object. On
    successful deletion, it will return true, else false will be returned.
    However, it is important to consider the following scenarios:

    • If the property which you are trying to delete does not exist, delete
      will not have any effect and will return true

    • If a property with the same name exists on the object's prototype
      chain, then, after deletion, the object will use the property from the
      prototype chain (in other words, delete only has an effect on own
      properties).

    • Any property declared with var cannot be deleted from the global scope
      or from a function's scope.

    • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function (expression).

    • Functions which are part of an object (apart from the
      global scope) can be deleted with delete.

    • Any property declared with let or const cannot be deleted from the scope within which they were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().

    下面的代码片段给出了另一个简单的示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var Employee = {
          age: 28,
          name: 'Alireza',
          designation: 'developer'
        }
       
        console.log(delete Employee.name);   // returns true
        console.log(delete Employee.age);    // returns true
       
        // When trying to delete a property that does
        // not exist, true is returned
        console.log(delete Employee.salary); // returns true

    有关更多信息和查看更多示例,请访问以下链接:

    https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/delete


    另一种解决方案,使用Array#reduce

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var myObject = {
     "ircEvent":"PRIVMSG",
     "method":"newURI",
     "regex":"^http://.*"
    };

    myObject = Object.keys(myObject).reduce(function(obj, key) {
      if (key !="regex") {           //key you want to remove
        obj[key] = myObject[key];
      }
      return obj;
    }, {});

    console.log(myObject);

    但是,它将改变原始对象。如果要创建一个没有指定键的新对象,只需将reduce函数赋给一个新变量,例如:

    (ES6)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    const myObject = {
      ircEvent: 'PRIVMSG',
      method: 'newURI',
      regex: '^http://.*',
    };

    const myNewObject = Object.keys(myObject).reduce((obj, key) => {
      key !== 'regex' ? obj[key] = myObject[key] : null;
      return obj;
    }, {});

    console.log(myNewObject);


    This post is very old and I find it very helpful so I decided to share the unset function I wrote in case someone else see this post and think why it's not so simple as it in PHP unset function.

    The reason for writing this new unset function, is to keep the index of all other variables in this hash_map. Look at the following example, and see how the index of"test2" did not change after removing a value from the hash_map.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    function unset(unsetKey, unsetArr, resort){
      var tempArr = unsetArr;
      var unsetArr = {};
      delete tempArr[unsetKey];
      if(resort){
        j = -1;
      }
      for(i in tempArr){
        if(typeof(tempArr[i]) !== 'undefined'){
          if(resort){
            j++;
          }else{
            j = i;
          }
          unsetArr[j] = tempArr[i];
        }
      }
      return unsetArr;
    }

    var unsetArr = ['test','deletedString','test2'];

    console.log(unset('1',unsetArr,true)); // output Object {0:"test", 1:"test2
    <hr>
    <p>
    There are a lot of good answers here but I just want to chime in that when using delete to remove a property in JavaScript, it is often wise to first check if that property exists to prevent errors.
    </p>

    <p>
    E.g
    </p>

    [cc lang="javascript"]var obj = {"property":"value","property2":"value
    <div class="
    suo-content">[collapse title=""]<ul><li>删除foo.bar即使bar不存在也有效,所以您的测试有点太多,imho。</li><li>@philho,这取决于你在哪里运行javascript。在node.js中,我认为这会导致服务器崩溃。</li><li><wyn>delete foo.bar;</wyn>只在foo不稳定或处于严格模式且foo是具有不可配置的bar属性的对象时抛出异常。</li><li>我不记得我对这个问题有什么看法,但我认为当foo本身不存在,而你试图删除它的属性时,这个问题可能会出现。</li><li>是的,您必须测试foo是否存在,否则foo.bar将抛出一个异常,但在删除它之前,您不需要检查该条是否存在。这是我评论的"太多"部分。-)</li><li>可能是我在检查属性本身以确定机器的状态或其他什么。例如,不必回答OP的问题。</li></ul>[/collapse]</div><hr>
    <p>
    Using ramda#dissoc you will get a new object without the attribute <wyn>regex</wyn>:
    </p>

    [cc lang="
    javascript"]const newObject = R.dissoc('regex', myObject);
    // newObject !== myObject

    您还可以使用其他函数来实现相同的效果-省略、选取…


    尝试以下方法。将Object属性值赋给undefined。然后是以东十一〔11〕号,以东十一〔12〕号。

    1
    2
    3
    4
    5
    6
    7
    8
     var myObject = {"ircEvent":"PRIVMSG","method":"newURI","regex":"^http://.*
    <div class="
    suo-content">[collapse title=""]<ul><li>也叫<wyn>JSON.parse(JSON.stringify({ ...myObject, regex: undefined }))</wyn>。</li></ul>[/collapse]</div><hr><P>使用ES6:</P><P>(破坏+扩展运算符)</P>[cc lang="javascript"]    const myObject = {
          regex:"
    ^http://.*",
          b: 2,
          c: 3
        };
        const { regex, ...noRegex } = myObject;
        console.log(noRegex); // => { b: 2, c: 3 }


    If you want to delete a property deeply nested in the object then you can use the following recursive function with path to the property as the second argument:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var deepObjectRemove = function(obj, path_to_key){
        if(path_to_key.length === 1){
            delete obj[path_to_key[0]];
            return true;
        }else{
            if(obj[path_to_key[0]])
                return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
            else
                return false;
        }
    };

    例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var a = {
        level1:{
            level2:{
                level3: {
                    level4:"yolo"
                }
            }
        }
    };

    deepObjectRemove(a, ["level1","level2","level3"]);
    console.log(a);

    //Prints {level1: {level2: {}}}


    您可以使用delete关键字简单地删除对象的任何属性。

    例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var obj = {key1:"val1",key2:"val2",key3:"val3
    <hr><P>考虑创建一个没有<wyn>"
    regex"</wyn>属性的新对象,因为程序的其他部分始终可以引用原始对象。因此,您应该避免操纵它。</P><P>[cc lang="javascript"]const myObject = {
       "
    ircEvent":"PRIVMSG",
       "
    method":"newURI",
       "
    regex":"^http://.*"
    };

    const { regex, ...newMyObject } = myObject;

    console.log(newMyObject);


    丹认为"删除"的速度非常慢,他发布的基准也受到了质疑。所以我自己在Chrome59中进行了测试。"删除"似乎慢了30倍:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var iterationsTotal = 10000000;  // 10 million
    var o;
    var t1 = Date.now(),t2;
    for (let i=0; i<iterationsTotal; i++) {
       o = {a:1,b:2,c:3,d:4,e:5};
       delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;
    }
    console.log ((t2=Date.now())-t1);  // 6135
    for (let i=0; i<iterationsTotal; i++) {
       o = {a:1,b:2,c:3,d:4,e:5};
       o.a = o.b = o.c = o.d = o.e = undefined;
    }
    console.log (Date.now()-t2);  // 205

    注意,我有目的地在一个循环周期中执行了多个"删除"操作,以最小化其他操作造成的影响。


    object.assign()对象.keys()数组.map())

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    const obj = {
       "Filters":[
            {
               "FilterType":"between",
               "Field":"BasicInformationRow.A0",
               "MaxValue":"2017-10-01",
               "MinValue":"2017-09-01",
               "Value":"Filters value"
            }
        ]
    };

    let new_obj1 = Object.assign({}, obj.Filters[0]);
    let new_obj2 = Object.assign({}, obj.Filters[0]);

    /*

    // old version

    let shaped_obj1 = Object.keys(new_obj1).map(
        (key, index) => {
            switch (key) {
                case"MaxValue":
                    delete new_obj1["MaxValue"];
                    break;
                case"MinValue":
                    delete new_obj1["MinValue"];
                    break;
            }
            return new_obj1;
        }
    )[0];


    let shaped_obj2 = Object.keys(new_obj2).map(
        (key, index) => {
            if(key ==="Value"){
                delete new_obj2["Value"];
            }
            return new_obj2;
        }
    )[0];


    */



    // new version!

    let shaped_obj1 = Object.keys(new_obj1).forEach(
        (key, index) => {
            switch (key) {
                case"MaxValue":
                    delete new_obj1["MaxValue"];
                    break;
                case"MinValue":
                    delete new_obj1["MinValue"];
                    break;
                default:
                    break;
            }
        }
    );

    let shaped_obj2 = Object.keys(new_obj2).forEach(
        (key, index) => {
            if(key ==="Value"){
                delete new_obj2["Value"];
            }
        }
    );


    你好,你可以试试这个简单的

    1
    2
    3
    4
    5
    6
    var obj = [];

    obj.key1 = {name:"John", room: 1234};
    obj.key2 = {name:"Jim", room: 1234};

    delete(obj.key1);

    试试这个

    1
    delete myObject['key'];

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    const myObject = {
           "ircEvent":"PRIVMSG",
           "method":"newURI",
           "regex":"^http://.*"
        };

    const { regex, ...other } = myObject;

    console.log(myObject)
    console.log(regex)
    console.log(other)


    使用土灰

    1
    2
    3
    4
    5
    import omit from 'lodash/omit';

    const prevObject = {test: false, test2: true};
    // Removes test2 key from previous object
    const nextObject = omit(prevObject, 'test2');

    使用RAMDA

    1
    R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}

    在javascript中删除属性

    这个页面上有许多不同的选项,不是因为大多数选项都是错误的,或者答案是重复的,而是因为适当的技术取决于您所处的环境以及您和/或您的团队试图完成的任务的目标。要明确回答你的问题,你需要知道:

  • 你要瞄准的ecmascript版本
  • 要删除其属性的对象类型的范围以及需要忽略的属性名称的类型(仅限字符串?符号?从任意对象映射的弱引用?多年来,这些都是JavaScript中的属性指针类型)
  • 您和您的团队使用的编程方法/模式。你喜欢功能性的方法,而突变在你的团队中是用原话描述的,还是使用了WildWest的面向对象的突变技术?
  • 您是希望用纯JavaScript实现这一点,还是希望&能够使用第三方库?
  • 回答完这四个查询后,为了满足您的目标,Javascript中基本上有四类"属性删除"。他们是:

    可变对象属性删除,不安全

    此类别用于在要保留/继续使用原始引用且代码中不使用无状态功能原则时对对象文本或对象实例进行操作。此类中的语法示例:

    1
    2
    3
    4
    5
    'use strict'
    const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
    delete iLikeMutatingStuffDontI[Symbol.for('amICool')] // true
    Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
    delete iLikeMutatingStuffDontI['amICool'] // throws

    这一类别是最古老、最直接和最广泛支持的财产移除类别。除了字符串之外,它还支持Symbol和数组索引,并且可以在除第一个版本外的每个版本的javascript中工作。但是,它是可变的,违反了一些编程原则,并且具有性能影响。当在严格模式下用于不可配置的属性时,它还可能导致未捕获的异常。

    基于REST的字符串属性省略

    此类别用于在需要非可变方法且不需要考虑符号键的情况下,以较新的ECMAScript风格在纯对象或数组实例上操作:

    1
    2
    3
    const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
    const { name, ...coolio } = foo // coolio doesn't have"name"
    const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

    可变对象属性删除,安全

    此类别用于在要保留/继续使用原始引用,同时防止在不可配置的属性上引发异常时对对象文本或对象实例进行操作:

    1
    2
    3
    4
    5
    'use strict'
    const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
    Reflect.deleteProperty(iLikeMutatingStuffDontI, Symbol.for('amICool')) // true
    Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
    Reflect.deleteProperty(iLikeMutatingStuffDontI, 'amICool') // false

    此外,虽然在适当的位置上改变对象不是无状态的,但是您可以使用Reflect.deleteProperty的功能特性来执行部分应用和其他在delete语句中不可能实现的功能技术。

    基于语法的字符串属性省略

    此类别用于在需要非可变方法且不需要考虑符号键的情况下,以较新的ECMAScript风格在纯对象或数组实例上操作:

    1
    2
    3
    const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
    const { name, ...coolio } = foo // coolio doesn't have"name"
    const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

    基于库的属性省略

    此类别通常允许更大的功能灵活性,包括在一个语句中忽略符号和多个属性:

    1
    2
    3
    4
    const o = require("lodash.omit")
    const foo = { [Symbol.for('a')]: 'abc', b: 'b', c: 'c' }
    const bar = o(foo, 'a') //"'a' undefined"
    const baz = o(foo, [ Symbol.for('a'), 'b' ]) // Symbol supported, more than one prop at a time,"Symbol.for('a') undefined"

    可以使用ES6析构函数和REST运算符。

    可以使用析构函数和rest运算符来删除属性。在您的示例中,regex被销毁(忽略),其余属性作为rest返回。

    1
    2
    3
    4
    5
    6
    7
    8
    const noRegex = ({ regex, ...rest }) => rest;
    const myObject = {
     "ircEvent":"PRIVMSG",
     "method":"newURI",
     "regex":"^http://.*"
    };

    console.log(noRegex(myObjext)) //=> { "ircEvent":"PRIVMSG","method":"newURI" }

    或者您可以动态排除这样的属性,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const myObject = {
     "ircEvent":"PRIVMSG",
     "method":"newURI",
     "regex":"^http://.*"
    };
    const removeProperty = prop => ({ [prop]: _, ...rest }) => rest

    const removeRegex = removeProperty('regex') //=> { "ircEvent":"PRIVMSG","method":"newURI" }
    const removeMethod = removeProperty('method') //=> { "ircEvent":"PRIVMSG","regex":"^http://.*" }

    @Johnstock,我们还可以使用javascript的原型概念向对象添加方法,以删除调用对象中可用的任何传递的键。

    以上答案不胜感激。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    var myObject = {
       "ircEvent":"PRIVMSG",
       "method":"newURI",
       "regex":"^http://.*"
    };

    // 1st and direct way
    delete myObject.regex;  // delete myObject["regex"]
    console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }

     // 2 way -  by using the concept of JavaScript's prototyping concept
    Object.prototype.removeFromObjectByKey = function(key) {
         // If key exists, remove it and return true
         if(this[key] !== undefined) {
               delete this[key]
               return true;
         }
         // Else return false
         return false;
    }

    var isRemoved = myObject.removeFromObjectByKey('method')
    console.log(myObject)  // { ircEvent: 'PRIVMSG' }

    // More examples
    var obj = { a: 45, b: 56, c: 67}
    console.log(obj) // { a: 45, b: 56, c: 67 }

    // Remove key 'a' from obj
    isRemoved = obj.removeFromObjectByKey('a')
    console.log(isRemoved); //true
    console.log(obj); // { b: 56, c: 67 }

    // Remove key 'd' from obj which doesn't exist
    var isRemoved = obj.removeFromObjectByKey('d')
    console.log(isRemoved); // false
    console.log(obj); // { b: 56, c: 67 }

    非常简单:

    1
    2
    3
    4
    5
    6
    7
    var myObject = {
       "ircEvent":"PRIVMSG",
       "method":"newURI",
       "regex":"^http://.*"
    };

    delete myObject.regex;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function removeProperty(obj, prop) {
        if(prop in obj){

        Reflect.deleteProperty(obj, prop);
        return true;
       } else {
        return false;
      }
    }

    从下面开始,您可以使用delete操作符。

    1
    2
    3
    4
    5
    6
    7
    8
    9
     var multiverse = {
            earth1:"Silver Age",
            earth2:"Golden Age"
        };

    delete multiverse.earth2;//will return true if it finds

    // Outputs: { earth1:"Silver Age" }
    console.log(multiverse);

    delete操作符也有一个return value.,如果它成功地删除了一个属性,它将返回true。如果由于属性不可写而未能删除该属性,则会删除cx1〔2〕,如果处于严格模式,则会引发错误。


    我还使用了lodash"unset"来实现嵌套对象的设置。只有这样,才需要编写小逻辑来获取omit方法所期望的属性键的路径。

  • 以数组形式返回属性路径的方法
  • 1
    2
    3
    4
    var a="bool""must"["range""price_index.final_price""gt""450""lt""500<hr><P>正如许多人所说,您可以使用"删除"(javascript属性)或"取消设置"(使用lodash)。</P><P>您也可以使用lodash属性"pick"只选取必要的对象属性。当您从对象中删除多个属性时,它将有所帮助。</P><P>用途如下:</P>[cc lang="javascript"]var _   = require("lodash");
    var obj = {"
    a":1,"b":2,"c":3};
    obj = _.pick(obj,["
    a","b"]);    
    //Now obj contains only 2 props {"
    a":1,"b":2}

    为了

    1
    2
    3
    4
    5
    var myObject = {
       "ircEvent":"PRIVMSG",
       "method":"newURI",
       "regex":"^http://.*"
    };

    删除myObject["regex"];您还知道键的索引,例如,您需要删除第二个键(regex)然后

    1
    2
    var key =  Object.keys(myObject)[2]
    delete myObject[key];

    很多时候我们需要在对象中基于索引的移除,但是记住对象中的键可能是上下位置,所以在使用时请小心。


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    function removeElement(elementId) {
        // Removes an element from the document
        var element = document.getElementById(elementId);
        element.parentNode.removeChild(element);
    }

    function addElement(parentId, elementTag, elementId, html) {
        // Adds an element to the document
        var p = document.getElementById(parentId);
        var newElement = document.createElement(elementTag);
        newElement.setAttribute('id', elementId);
        newElement.innerHTML = html;
        p.appendChild(newElement);
    }

    有关详细信息,请单击此