克隆一个js对象,除了一个键 [英] clone a js object except for one key

查看:423
本文介绍了克隆一个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;

将被透析

 use strict; 

函数_objectWithoutProperties(obj,keys){var target = {}; for(var i in obj){if(keys.indexOf(i)> = 0)continue; if(!Object.prototype.hasOwnProperty.call(obj,i))继续; target [i] = obj [i]; }返回目标; }

var x = {a:1,b:2,c:3,z:26};
var b = x.b;

var y = _objectWithoutProperties(x,[b]);


I have a flat JS object:

{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)?

解决方案

If you use Babel you can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:

let x = {a: 1, b: 2, c: 3, z:26};
let {b, ...y} = x;

and it will be transpiled into:

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

这篇关于克隆一个js对象,除了一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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