简体   繁体   English

克隆javascript对象的一部分

[英]Clone part of javascript object

I have a big JS object with many nested objects. 我有一个带有许多嵌套对象的大型JS对象。 For example: 例如:

var A = {
    'b': {
        c: [1],
        d: {
            e: {
                f: 'g'
            }
        }
    }
};

I need to create an object "B" looks like the object "A", but array "bc" should contain another one item: 我需要创建一个看起来像对象“ A”的对象“ B”,但是数组“ bc”应该包含另一个项:

var B = {
    'b': {
        c: [1, 2],
        d: {
            e: {
                f: 'g'
            }
        }
    }
};

The object "A" should not be changed. 对象“ A”不应更改。

I know two ways to do it: 我知道两种方法:

1 Deep clone JS object: 1个深度克隆JS对象:

var B = JSON.parse(JSON.stringify(A)); // or with lodash: _.cloneDeep(A)
B.b.c.push(2);

2 Clone only those objects and arrays that I need to clone: 2仅克隆那些我需要克隆的对象和数组:

var B = Object.assign({}, A);
B.b = Object.assign({}, B.b);
B.b.c = B.b.c.slice(0);
B.b.c.push(2);

I'm afraid that the first way is resource intensive. 恐怕第一种方法会占用大量资源。 I don't need to clone all object. 我不需要克隆所有对象。 And the second way has too many code. 第二种方式有太多的代码。 There is a little object in my example but it can be really big objects in my application. 在我的示例中有一个小对象,但是在我的应用程序中它可能是很大的对象。

How to create the object "B" of the most optimal way? 如何创建最佳方式的对象“ B”?

JSON.stringify / .parse is certainly the easiest way to deep-clone a (simple) object but, as you said, it involves serializing and parsing objects and it's totally not the most efficient way. JSON.stringify / .parse当然是深度克隆(简单)对象的最简单方法,但是,正如您所说的,它涉及序列化和解析对象,这绝对不是最有效的方法。

Luckily, things have become nicer from ES6. 幸运的是,ES6使事情变得更好了。 And with ESNext, you can spread objects too: 借助ESNext,您也可以传播对象:

var B = { ...A };

Of course, there's still your problem with bc , but that has to be adjusted manually: 当然, bc仍然存在您的问题,但是必须手动调整:

var B = { ...A, b: { ...A.b, c: [1, 2] }};

Here's Babel's plugin for object spread operator: https://babeljs.io/docs/plugins/transform-object-rest-spread/ 这是对象传播运算符的Babel插件: https : //babeljs.io/docs/plugins/transform-object-rest-spread/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM