JavaScript如何从复制的对象中删除密钥? [英] JavaScript How to delete key from copied object?

查看:64
本文介绍了JavaScript如何从复制的对象中删除密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有查询对象

var q = {
    age: 10, 
    'profile.contry': 'india'
};

现在我复制 q 变量并删除来自重复变量的密钥。

Now I duplicate the q variable and remove key from a duplicate variable.

var duplicateQ = q;
delete duplicateQ['profile.contry']; // I have removed 'profile.country' from duplicateQ.

console.log(q); //Object { age: 10 }
console.log(duplicateQ); //Object { age: 10 }

为什么两个变量都受到影响?如何从其中一个属性中删除属性?

Why are both the variables affected? How can I remove the property from only one of them?

推荐答案

您没有重复 q ,相反,你正在复制对不同变量的引用。

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

两者 q duplicateQ 指向相同的对象,即计算机内存中的相同位置。

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

这篇关于JavaScript如何从复制的对象中删除密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆