From 978a209e3e3927c96b0b57cbff6e42e751d50369 Mon Sep 17 00:00:00 2001 From: Justin Schroeder Date: Sun, 19 Apr 2020 14:34:25 -0400 Subject: [PATCH] Adds array support to cloneDeep --- examples/specimens/SpecimenGroup.vue | 55 ++++++++++++++++++---------- src/libs/utils.js | 6 ++- test/unit/utils.test.js | 13 +++++++ 3 files changed, 54 insertions(+), 20 deletions(-) diff --git a/examples/specimens/SpecimenGroup.vue b/examples/specimens/SpecimenGroup.vue index fbcd9d6..388db80 100644 --- a/examples/specimens/SpecimenGroup.vue +++ b/examples/specimens/SpecimenGroup.vue @@ -1,27 +1,38 @@ @@ -29,7 +40,13 @@ export default { data () { return { - groupValue: null + formResult: null, + saveValues: null + } + }, + methods: { + save (values) { + this.saveValues = values } } } diff --git a/src/libs/utils.js b/src/libs/utils.js index a8598ae..75ae189 100644 --- a/src/libs/utils.js +++ b/src/libs/utils.js @@ -178,7 +178,11 @@ export function isValueType (data) { * case of needing to unbind reactive watchers. */ export function cloneDeep (obj) { - const newObj = {} + if (typeof obj !== 'object') { + return obj + } + const isArr = Array.isArray(obj) + const newObj = isArr ? [] : {} for (const key in obj) { if (obj[key] instanceof FileUpload || isValueType(obj[key])) { newObj[key] = obj[key] diff --git a/test/unit/utils.test.js b/test/unit/utils.test.js index a92a924..a67fc49 100644 --- a/test/unit/utils.test.js +++ b/test/unit/utils.test.js @@ -116,6 +116,19 @@ describe('cloneDeep', () => { const clone = cloneDeep({ a: 123, b: c }) expect(clone.b === c).toBe(false) }) + + it('retains array structures inside of a pojo', () => { + const obj = { a: 'abcd', d: ['first', 'second'] } + const clone = cloneDeep(obj) + expect(Array.isArray(clone.d)).toBe(true) + }) + + it('removes references inside array structures', () => { + const deepObj = {foo: 'bar'} + const obj = { a: 'abcd', d: ['first', deepObj] } + const clone = cloneDeep(obj) + expect(clone.d[1] === deepObj).toBe(false) + }) }) describe('snakeToCamel', () => {