我有一个扁平的JS对象:
{a: 1, b: 2, c: 3, ..., z:26}
我想克隆除一个元素之外的对象:
{a: 1, c: 3, ..., z:26}
最简单的方法是什么(如果可能,最好使用es6/7)?
如果使用Babel,则可以使用以下语法将属性b从x复制到变量b,然后将其余属性复制到变量y中:
let x = {a: 1, b: 2, c: 3, z:26}; let {b, ...y} = x;
并且将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"]);
var clone = Object.assign({}, {a: 1, b: 2, c: 3}); delete clone.b;
或者如果您接受未定义的财产:
var clone = Object.assign({}, {a: 1, b: 2, c: 3}, {b: undefined});
要添加到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};
Babel REPL中的演示
资源:
https://twitter.com/ydkjs/status/699845396084846592
对于那些不能使用ES6的人,你可以使用lodash
或underscore
.
_.omit(x, 'b')
或者ramda
.
R.omit('b', x)
我使用这种单线程ES6语法,
const obj = {a: 1, b: 2, c: 3, d: 4};
const clone = (({b, c, ...others}) => ({...others}))(obj); // remove b and c
console.log(clone);
你可以为它编写一个简单的辅助函数.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}
另请注意,它比Object.assign更快,然后删除:http://jsperf.com/omit-key
也许是这样的:
var copy = Object.assign({}, {a: 1, b: 2, c: 3}) delete copy.c;
这够好吗?或者c
实际上无法复制?
使用对象分解
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}
嘿,当你试图复制一个对象然后删除一个属性时,你似乎遇到了引用问题.在某些地方你必须分配原始变量,以便javascript创建一个新值.
我使用的简单技巧(可能是可怕的)就是这个
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"}