1

I want to clone an obj with some react elements inside. When I clone the obj
with JSON.parse(JSON.stringify(obj)). It removes $$typeof: Symbol(react.element).

const elm = <span>A Simple Span</span>
console.log(elm)
const copyOfElm = JSON.parse(JSON.stringify(elm))
console.log(copyOfElm);

I want to know how to clone in a way that it does not remove the property.

5
  • 1
    You might want to know more about javascript property descriptors. I think that explains why all properties aren't displayed in JSON.stringify, and why you cannot use it to clone everything. Commented Jan 23, 2019 at 16:56
  • 1
    React.cloneElement? Commented Jan 23, 2019 at 16:57
  • 1
    JSON.parse(JSON.stringify(something)) is not a reliable way to clone objects. It works sometimes, but as you've found it doesn't work all the time. Commented Jan 23, 2019 at 16:57
  • I want to know why $$typeof is not present in copyOfElm Commented Jan 23, 2019 at 16:58
  • 3
    Because JSON.stringify ignores all Symbol properties. Commented Jan 23, 2019 at 17:02

1 Answer 1

4

You can use Object.assign e.g.

const copyOfElm = Object.assign({}, elm);
Sign up to request clarification or add additional context in comments.

3 Comments

what if i wanna clone object like const elm = { innerHTML:[ <span>A Simple Span</span>, <span>A Simple Span</span> ] }
Object.assign is for objects not loops. For this purpose you can try lodash.com/docs/#cloneDeep
Thanks umair i got my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.