JavaScript How to delete key from copied object?

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • You aren't duplicating q , instead, you're copying a reference to different variable.

    Both q and duplicateQ point to the same object, the same location in your computer's memory.

    In order to make this work, you're going to have to clone the object, then you can delete (/ modify) individual properties on the separate variables.

    A quick-and-dirty example:

    var a = { a: 1, b: 2 },
        b = JSON.parse(JSON.stringify(a));
    
    delete b.a;
    
    document.body.textContent = JSON.stringify(a) + ' ' + JSON.stringify(b);

    It's because q and duplicateQ refer to the same object. Thus, when you delete a property on one object, it effects both (since they both point to the same object).

    You need to copy/clone the object.

    In ES6, you can use the .assign() method:

    var q = {age:10, 'profile.contry': 'india'};
    var duplicateQ = Object.assign({}, q);
    delete duplicateQ['profile.contry'];
    

    Output:

    console.log(q);
    // {age: 10, profile.contry: "india"}
    
    console.log(duplicateQ);
    // Object {age: 10}
    
    链接地址: http://www.djcxy.com/p/24768.html

    上一篇: Object.assign保持对原始对象的引用

    下一篇: JavaScript如何从复制的对象中删除键?