除了一个键之外,如何克隆一个 JavaScript 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34698905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I clone a JavaScript object except for one key?
提问by fox
I have a flat JS object:
我有一个扁平的 JS 对象:
{a: 1, b: 2, c: 3, ..., z:26}
I want to clone the object except for one element:
我想克隆除一个元素之外的对象:
{a: 1, c: 3, ..., z:26}
What's the easiest way to do this (preferring to use es6/7 if possible)?
最简单的方法是什么(如果可能,最好使用 es6/7)?
回答by Ilya Palkin
If you use Babelyou can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:
如果您使用Babel,您可以使用以下语法将属性 b 从 x 复制到变量 b 中,然后将其余属性复制到变量 y 中:
let x = {a: 1, b: 2, c: 3, z:26};
let {b, ...y} = x;
and it will be transpiledinto:
并且将transpiled到:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var x = { a: 1, b: 2, c: 3, z: 26 };
var b = x.b;
var y = _objectWithoutProperties(x, ["b"]);
回答by madox2
var clone = Object.assign({}, {a: 1, b: 2, c: 3});
delete clone.b;
or if you accept property to be undefined:
或者如果您接受未定义的属性:
var clone = Object.assign({}, {a: 1, b: 2, c: 3}, {b: undefined});
回答by Paul K?gel
To add to Ilya Palkin's answer: you can even dynamically remove keys:
要添加到 Ilya Palkin 的答案:您甚至可以动态删除键:
const x = {a: 1, b: 2, c: 3, z:26};
const objectWithoutKey = (object, key) => {
const {[key]: deletedKey, ...otherKeys} = object;
return otherKeys;
}
console.log(objectWithoutKey(x, 'b')); // {a: 1, c: 3, z:26}
console.log(x); // {a: 1, b: 2, c: 3, z:26};
Source:
来源:
回答by dashmug
For those who can't use ES6, you can use lodash
or underscore
.
对于那些不会使用 ES6 的人,可以使用lodash
或underscore
。
_.omit(x, 'b')
Or ramda
.
或者ramda
。
R.omit('b', x)
回答by vdegenne
I use this ESNext one liner
我用这个 ESNext one liner
const obj = { a: 1, b: 2, c: 3, d: 4 }
const clone = (({ b, c, ...o }) => o)(obj) // remove b and c
console.log(clone)
If you need a general purpose function :
如果您需要通用功能:
function omit(obj, props) {
props = props instanceof Array ? props : [props]
return eval(`(({${props.join(',')}, ...o}) => o)(obj)`)
}
// usage
const obj = { a: 1, b: 2, c: 3, d: 4 }
const clone = omit(obj, ['b', 'c'])
console.log(clone)
回答by just-boris
You can write a simple helper function for it. Lodash has a similar function with the same name: omit
您可以为它编写一个简单的辅助函数。Lodash 有一个类似的同名函数:省略
function omit(obj, omitKey) {
return Object.keys(obj).reduce((result, key) => {
if(key !== omitKey) {
result[key] = obj[key];
}
return result;
}, {});
}
omit({a: 1, b: 2, c: 3}, 'c') // {a: 1, b: 2}
Also, note that it is faster than Object.assign and delete then: http://jsperf.com/omit-key
另外,请注意它比 Object.assign 快,然后删除:http: //jsperf.com/omit-key
回答by Ivan Nosov
Using Object Destructuring
使用对象解构
const omit = (prop, { [prop]: _, ...rest }) => rest;
const obj = { a: 1, b: 2, c: 3 };
const objWithoutA = omit('a', obj);
console.log(objWithoutA); // {b: 2, c: 3}
回答by clean_coding
Maybe something like this:
也许是这样的:
var copy = Object.assign({}, {a: 1, b: 2, c: 3})
delete copy.c;
Is this good enough? Or can't c
actually get copied?
这够好吗?或者c
实际上不能被复制?
回答by Chris Fust
Hey seems like you run in to reference issues when you're trying to copy an object then deleting a property. Somewhere you have to assign primitive variables so javascript makes a new value.
嘿,当您尝试复制对象然后删除属性时,您似乎遇到了引用问题。您必须在某个地方分配原始变量,以便 javascript 生成一个新值。
Simple trick (may be horrendous) I used was this
我使用的简单技巧(可能很可怕)是这个
var obj = {"key1":"value1","key2":"value2","key3":"value3"};
// assign it as a new variable for javascript to cache
var copy = JSON.stringify(obj);
// reconstitute as an object
copy = JSON.parse(copy);
// now you can safely run delete on the copy with completely new values
delete copy.key2
console.log(obj)
// output: {key1: "value1", key2: "value2", key3: "value3"}
console.log(copy)
// output: {key1: "value1", key3: "value3"}
回答by goldins
Here's an option for omitting dynamic keys that I believe has not been mentioned yet:
这是省略我认为尚未提及的动态键的选项:
const obj = { 1: 1, 2: 2, 3: 3, 4: 4 };
const removeMe = 1;
const { [removeMe]: removedKey, ...newObj } = obj;
removeMe
is aliased as removedKey
and ignored. newObj
becomes { 2: 2, 3: 3, 4: 4 }
. Note that the removed key does not exist, the value was not just set to undefined
.
removeMe
别名为removedKey
并被忽略。newObj
变成{ 2: 2, 3: 3, 4: 4 }
. 请注意,删除的键不存在,该值不只是设置为undefined
。