除了一个键之外,如何克隆一个 JavaScript 对象? [英] How can I clone a JavaScript object except for one key?

查看:23
本文介绍了除了一个键之外,如何克隆一个 JavaScript 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扁平的 JS 对象:

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}

最简单的方法是什么(如果可能,最好使用 es6/7)?

What's the easiest way to do this (preferring to use es6/7 if possible)?

推荐答案

如果你使用 Babel 你可以使用下面的将属性 b 从 x 复制到变量 b 然后将其余属性复制到变量 y 的语法:

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;

它将被转译为:

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

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

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